Javascript Fetch API and MYSQL

My purpose is to select data from MYSQL database using Javascript Fetch API. I can do it using AJAX as follows:

File ‘getUser.php’:

<?php
$con = mysqli_connect('hostname','username','password','database');
$q = intval($_POST['q']);
if ($con) {
  $sql = "SELECT * FROM user WHERE id = '".$q."'";
  $result = mysqli_query($con, $sql);
  $row = mysqli_fetch_array($result)
  if ($row) {
      echo "$row[1]";
  }
}
?>

File ‘index.php’:

<script>
function showUser(str) {
  let xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      ... = this.responseText;
    }
  };
  xmlhttp.open("POST", "getUser.php");
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("q="+str);
}
</script>

With Fetch API I tried this:

<script>
let file = "getUser.php";
fetch (file)
  .then(x => x.text())
  .then(y => ... = y);
</script>

But I cannot find how can I pass the value of ‘str’ to file ‘getUser.php’ so as to extract from the database the data for the specific person.

remove duplicates from array of objects array

how do I remove duplicate from below JSON
checking website_name and only keeping num_followers with greatest value per date

the output should be just one value of website name in each websites array for each date

[
    {
        "date": "2022-02-15",
        "websites": [
            {
                "website_name": "instagram",
                "num_followers": "123146780"
            },
            {
                "website_name": "instagram",
                "num_followers": "123134954"
            },
            {
                "website_name": "tiktok",
                "num_followers": "123184229"
            }
        ]
    },
    {
        "date": "2022-02-14",
        "websites": [
            {
                "website_name": "instagram",
                "num_followers": "123057832"
            },
            {
                "website_name": "tiktok",
                "num_followers": "123058141"
            },
            {
                "website_name": "tiktok",
                "num_followers": "123058219"
            },
            {
                "website_name": "instagram",
                "num_followers": "123059280"
            }
        ]
    }
]

Laravel and Redmine Database // query builder with eloquent

I’m new in Laravel (5.4). I work on redmine database and I want to have users role. The tables are :

users : id, login, hashed_password,...
members : id, user_id, project_id, created_on, mail_notification
member_roles : id, member_id (foreign key), role_id, inherited_from
roles : id, name,...

My query works perfectly but I want to make it fluent without “->select(…)” :

$membersRole = DB::connection('redmine')
      ->select('SELECT roles.name  as role, user_id
        FROM users, members, projects, member_roles, roles
        WHERE projects.id = ?
                  AND members.user_id = ?
                  AND members.project_id = projects.id
                  AND members.id = member_roles.member_id
                  AND roles.id = member_roles.role_id
        LIMIT 1', [$id, $userId]);

How can I do it ?

Undefined variable: name Laravel

I am trying to make an edit form but when I fire the editData Function it Gives me the error
which is ‘Undefined variable: name‘.I tried so Hard to Find the solution but nothing works
Maybe I’m missing something which I don’t know. I Need Help to Move Forward.

Here is my code:-

ProductControlller.php

<?php

namespace AppHttpControllers;

use AppProduct;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
class ProductController extends Controller
{
    
    public function InsertForm()
    {
    return view('prodInsert');
    }


    
    public function Prodcreate(Request $request)
    {
        $pName=$request->input('pname');
        $pPrice=$request->input('pprice');
        $pDesc=$request->input('pdesc');
        $pQuantity=$request->input('pquantity');

            $data=array('pname' =>$pName,'pprice' =>$pPrice,'pdesc' =>$pDesc,'pquantity' =>$pQuantity);
        DB::table('products')->insert($data);
        echo "Record Inserted Succefully<br>";
        echo "<a href='/Display'>Display Data</a><br>";
        echo "<a href='/prodInsert'>Add Product</a>";


    }

 
    public function selectData(Request $request)
    {
        $tabledata=DB::select('select * from products');
        return view('Display',['tabledata'=>$tabledata]);
       }

    public function deleteData(Request $request,$id){
        DB::table('products')->delete($id);
        return redirect('Display');

        }
      public function show($id)
        {
            $tabledata=DB::select('select * from products where id = ?',[$id]);
            return view('editform',['tabledata'=>$tabledata]);
        }

 
    public function editData(Request $request,$id)
    {
         $pName=$request->input('name');
        $pPrice=$request->input('price');
        $pDesc=$request->input('desc');
        $pQuantity=$request->input('quantity');

         DB::update('update products set pName=?','pPrice=?','pDesc=?','pQuantity=?',[$name,$price,$desc,$quantity,$id]);


   
    }
   

}

And this is my EditForm.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>PROD INSERT</title>
</head>
<body>

    <form action="/edit/<?php echo $tabledata[0]->id; ?>">

    @csrf
    <h4 align="center"><a href="Display"> Click here</a> Edit</h4>

    <table align="center">
        <tr>
            <td>Product name</td>
            <td><input type="text" name="name" value="<?php echo$tableData[0]->product_name; ?>"></td>
        </tr>
        <tr>
            <td>Product Price</td>
            <td><input type="text" name="price"></td>
        </tr>
        <tr>
            <td>Product Description</td>
            <td><input type="text" name="desc"></td>
        </tr>
        <tr>
            <td>Product Quantity</td>
            <td><input type="text" name="quantity"></td>
            <br>
        </tr>

            <td><input type="submit" name="submit"></td>

        
    </table>
</form>


</body>
</html>

I can provide more code if needed.
Thanks for Your Support 🙂

Multi auth with laravel sanctum

I am building a home service application with laravel for backend and react for frontend. So I use laravel sanctum for session-based authentication. In the future, I will probably need mobile application too. So, sanctum is the best choice possible.

I have two types of users. user and worker. They are in separate tables in database and I want to use multiple guards to separately authenticate them.

I have used the answer in this link and it does not work.
In my auth.php config file, I use these guards and providers:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'user' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
        'worker' => [
            'driver' => 'sanctum',
            'provider' => 'workers',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppModelsUser::class,
        ],
        'workers' => [
            'driver' => 'eloquent',
            'model' => AppModelsWorker::class,
        ],
    ],

But when I try to log in user in my controller:

auth('user')->login($user);

It gives me the following error:

"message": "Method Illuminate\Auth\RequestGuard::login does not exist.",

Actually, I tried to use default sanctum guard for user and log user in using ‘web’ guard:

auth('web')->login($user);

and It works, But an authenticated user can have access to the routes that need worker authentication:

    Route::prefix('worker')->name('worker.')->middleware(['auth:worker'])->group(function () {
         // ...
    });

So what should I do?

Retrieve sessionStorage variable mid way through a multi-step popup form

I would like to retrieve the value of a sessionStorage variable that was set in step 1 of a multi-step pop up to help in the conditional display of text in step 3. All five steps sit within a form and every post is handled by AJAX routines and are working fine.

Does anyone have any ideas about how I can pass the variable (selectedRole) back through to the front end from AJAX so I can use it in step 3?

My code to save the variable is as follows:-

    function setUpPopupRegistrationForm() {
        
        $('.js-popup-register-button').on('click', function() {
           
            let storage = window.sessionStorage;
            let selectedRole = this.dataset.role;
            
            storage.clear('selectedRole');
            storage.setItem('selectedRole', selectedRole);
            
            navigateToNextStep(this);
            
        });
        
    }
<div class="form__step js-popup-register-step" data-step="1">
  <h3>
    <?php the_field('title_1', 'option'); ?>
  </h3>
  <div class="d-flex flex-column flex-sm-row justify-content-between">
    <div class="button button--blue js-popup-register-button" data-role="member"> <span>Member</span>
    </div>
    <div class="button js-popup-register-button" data-role="guest"><span>Guest</span></div>
  </div>
</div>

ErrorException require(/vendor/magento/framework/registration.php): failed to open stream: No such file or directory in magento 2.3.7

i have two Magento projects,

website1 with :
-Magento version 2.3.1
-php fpm7.1
-mysql 5.7
-apache2 2.4.41
-composer 1
-in the file /etc/apache2/sites-available/website1.app.local.fr.conf

<VirtualHost *:80>
    ServerName website1.app.local.fr
    ServerAlias bo.website1.app.local.fr
    DocumentRoot "/var/www/html/website1/web"

    # Sources
    <Directory "/var/www/html/ecom-web/web">
        Options Indexes FollowSymLinks MultiViews Includes
        AllowOverride all
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>
    
    <FilesMatch .php$>
    SetHandler "proxy:unix:/run/php/php7.1-fpm.sock|fcgi://localhost"
    </FilesMatch>

    # Logs
        ErrorLog "/var/log/apache2/website1.error_log"
        CustomLog "/var/log/apache2/website1.access_log" common
</VirtualHost>

# SSL
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName website1-web.app.local.fr
        ServerAlias bo.website1-web.app.local.fr
        DocumentRoot "/var/www/html/website1/web"

    # SSL
    SSLEngine on
    SSLCertificateFile "/var/www/html/website1/ssl/website1.app.local.fr.crt"
    SSLCertificateKeyFile "/var/www/html/website1/ssl/website1.app.local.fr.key"

        # Sources
        <Directory "/var/www/html/website1/web">
            Options Indexes FollowSymLinks MultiViews Includes
            AllowOverride all
            Order allow,deny
            Allow from all
            Require all granted
        </Directory>
        
        <FilesMatch .php$>
    SetHandler "proxy:unix:/run/php/php7.1-fpm.sock|fcgi://localhost"
    </FilesMatch>

        # Logs
        ErrorLog "/var/log/apache2/website1.error_log"
        CustomLog "/var/log/apache2/website1.access_log" common
    </VirtualHost>
</IfModule>

and wibsite2 with :
-Magento version 2.3.7
-php fpm7.4
-mysql 5.7
-apache2 2.4.41
-composer 2
-in the file /etc/apache2/sites-available/website2.app.local.fr.conf

<VirtualHost *:80>
    ServerName website2.app.local.fr
    ServerAlias bo.website2.app.local.fr
    DocumentRoot "/var/www/html/website2/web"

    # Alias
    Alias "/media" "/var/www/html/website2/web/pub/media"

    # Sources
    <Directory "/var/www/html/website2/web">
        Options Indexes FollowSymLinks MultiViews Includes
        AllowOverride all
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>
    
    <FilesMatch .php$>
      SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
    </FilesMatch>

    # Logs
        ErrorLog "/var/log/apache2/website2.error_log"
        CustomLog "/var/log/apache2/website2.access_log" common
</VirtualHost>

# SSL
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName website2.app.local.fr
        ServerAlias bo.website2.app.local.fr
        DocumentRoot "/var/www/html/website2/web"

        # SSL
        SSLEngine on
        SSLCertificateFile "/var/www/html/website2/ssl/website2.app.local.fr.crt"
        SSLCertificateKeyFile "/var/www/html/website2/ssl/website2.app.local.fr.key"

        # Alias
        Alias "/media" "/var/www/html/website2/web/pub/media"

        # Sources
        <Directory "/var/www/html/website2/web">
            Options Indexes FollowSymLinks MultiViews Includes
            AllowOverride all
            Order allow,deny
            Allow from all
            Require all granted
        </Directory>
        
        <FilesMatch .php$>
       SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
    </FilesMatch>

        # Logs
        ErrorLog "/var/log/apache2/website2.error_log"
        CustomLog "/var/log/apache2/website2.access_log" common
    </VirtualHost>
</IfModule>

i have following this tuto https://www.digitalocean.com/community/tutorials/how-to-run-multiple-php-versions-on-one-server-using-apache-and-php-fpm-on-ubuntu-18-04-fr#etape-4-test-des-deux-sites-web

the problem now is that i can run website1 perfectly with no problem with setup:upgrade,composer install… and i can access to the website by the browser, but the website2 can’t be accessible by browser, and it tells me the error below when I run composer install

 [ErrorException]                                                                                                                   
  require(vendor/magento/framework/registration.php): failed to open stream: No such file or directory  

any help please?

Get all ads data with ads images in one query

1st table name my_ads and entries

+----+-------------+--------+----------+---------+
| id | title       | gender | country  | user_id |
+----+-------------+--------+----------+---------+
| 35 | NOman Javed | male   | Pakistan | 1       |
| 34 | Noman Javed | male   | Pakistan | 1       |
| 33 | Noman Javed | male   | Pakistan | 1       |
| 32 | Noman Javed | male   | Pakistan | 1       |
| 31 | Noman Javed | male   | Pakistan | 1       |
+----+-------------+--------+----------+---------+

2nd table ads_images

+----+-----------+---------------------------------+
| id | my_ads_id | image_path                      |
+----+-----------+---------------------------------+
| 28 | 35        | 1645180564-Screenshot-(529).png |
| 27 | 35        | 1645180562-Screenshot-(528).png |
| 26 | 35        | 1645180558-Screenshot-(527).png |
| 25 | 34        | 1645180318-Screenshot-(529).png |
| 24 | 34        | 1645180316-Screenshot-(528).png |
+----+-----------+---------------------------------+

I had written the query and combined it in one array value but I want it to be done with one query.

$all_ads = DB::table('my_ads')->get();

$my_ads_images = DB::table('ads_images')->select('id','my_ads_id', 'image_path')- 
>groupBy('my_ads_id')->get();

then compile with both tables values in one array on sub-index

foreach($all_ads as $ads_key => $ads) {

    $my_ads_array[$ads_key]['id'] = $ads->id;
    $my_ads_array[$ads_key]['title'] = $ads->title;

    foreach($my_ads_images as $my_ads_image) {
        if($ads->id == $my_ads_image->my_ads_id) {
            $my_ads_array[$ads_key]['image_path'] = $my_ads_image->image_path;
        }
    }
}

Can I write query to achieve $my_ads_array[$ads_key]['image_path'] = array of images here with one query. I am using Laravel 8 with MySQL.

I know it’s a basic query but I don’t know how it will work. I tried joins but that didn’t work for me don’t know why.

Looking for output like this:

[0] => Array
    (
        [id] => 35
        [title] => Noman Javed
        [gender] => male            
        [description] => Height: 5.6''
        [country] => Pakistan
        [image_path] => Array
            (
                [0] => 1645180558-Screenshot-(527).png
                [1] => 1645180562-Screenshot-(528).png
                [2] => 1645180564-Screenshot-(529).png
            )

        [created_at] => 2022-02-18 10:35:49

    )

Thanks in Advance in case sort this out.

How to set cookie value properly with $_SERVER[‘REQUEST_URI’]?

I have a Google AdWords campaign, so when users click on the ad it links them to a certain page. The page URL has a specific Google Ad string, so using it, I want to change some colors on all pages, not only one.

I’m trying to use $_SERVER['REQUEST_URI'] and setcookies() function. Let’s say that the Google Ad string is adword. So when the ad was clicked it linked to https://example.com/adword/ page and I get this slug string and set to cookies a value:

$cookie_val = '';
if (strpos($_SERVER['REQUEST_URI'], "adword") && !isset($_COOKIE['ad_cookies'])){
    setcookie('ad_cookies', 'myvalue', time()+(3600*6));  /* expire in 6 hours */
    $cookie_val = $_COOKIE['ad_cookies'];
}

I though then I can use this cookie value everywhere, for example by changing class name of a div:

<div class="page <?php echo $cookie_val ?>">

But it only works on one page https://example.com/adword/.

So my question is, how can I use this cookie value on every page when a user clicked the ad? Thanks in advance!

Betheme – On related posts, change read more button text for specific category

I am using Betheme on WordPress.

Under the related posts section, is it possible to change the ‘read more’ button for a specific post category?

I’ve created a podcast page, so would prefer the text to read ‘listen now’ just for that category.

You can translate the text in the theme options, but this applies to the whole site, and I would like it just for the specific category – podcasts (id-1396).

Send Email using GetResponse API keys

I have a WordPress site with getResponse plugin.

I have a registration form which should confirm the email of the user, then the user should be registered in the database.
I have an ajax call when the user submits the form, it gets the username and email to check if the email or username is already registered in the site.

The form html looks like this

<div id="td-register-div">
  <div class="td_display_err"></div>
  <form id="register-form" action="#" method="post">
    <div class="td-login-input">
      <input class="td-login-input" type="text" name="register_email" id="register_email">
      <label for="register_email">Your Email</label>
    </div>
    <div class="td-login-input">
      <input class="td-login-input" type="text" name="register_user" id="register_user">
      <label for="register_user">Your Username</label>
    </div>
    <input type="button" name="register_button" id="register_buttonn" value="Register">
  </form>
</div>

jQuery looks like this

$("#registerForm #register_buttonn").click(function(e){
    e.preventDefault();
    var user_email = $("#registerForm #register_email").val();
    var user_name = $("#registerForm #register_user").val();
    if (user_email == "" || user_name == "") {
        $("#td-register-div > .td_display_err").html("Email and username required");
        $("#td-register-div > .td_display_err").css("display", "block");
    } else{
        jQuery.ajax({
            type: "post",
            url: my_ajax_object.ajax_url,
            data : {action: "user_register_ajax", user_email: user_email, user_name: user_name},
            success: function(response){
                $("#td-register-div > .td_display_err").css("display", "block");
                $("#td-register-div > .td_display_err").html(response);
            }
        });
    }
});

function.php looks like this

function user_register_ajax(){
global $wpdb;
//Get username and email
$user_email = $_REQUEST['user_email'];
$user_name = $_REQUEST['user_name'];
//Check if username or email already exists
$check_username = "SELECT * FROM wp_users WHERE user_login = '".$user_name."'";
$userNameResult = $wpdb->get_results($check_username, OBJECT);
$check_useremail = "SELECT * FROM wp_users WHERE user_email = '".$user_email."'";
$userEmailResult = $wpdb->get_results($check_useremail, OBJECT);
if (count($userNameResult) != 0) {
    echo "Username already taken";
    die();
} else if(count($userEmailResult) != 0){
    echo "Email already exists";
    die();
} else{
    $url = 'https://api.getresponse.com/v3/transactional-emails';

    $params = array(
        'fromFieldId' => '[email protected]',     
        'subject'     => 'subject',
        'content'     => 'Message',
        'to'          => '[email protected]',
    );

    $curl = curl_init($url);
    // Set the CURLOPT_RETURNTRANSFER option to true
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // Set the CURLOPT_POST option to true for POST request
    curl_setopt($curl, CURLOPT_POST, true);
    // Set the request data as JSON using json_encode function
    curl_setopt($curl, CURLOPT_POSTFIELDS,  json_encode($params));
    // Set custom headers for X-Auth-Token, needed for Getresponse API
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
      'X-Auth-Token: api-key XXXX',
      'Content-Type: application/json'
    ]);

    // Execute cURL request with all previous settings
    ob_start();
    curl_exec($curl);
    // close the connection, release resources used
    curl_close($curl);      
    ob_end_clean();
    echo "Check your mail and enter OTP";
    die();
  }
}
add_action('wp_ajax_nopriv_user_register_ajax', 'user_register_ajax');
add_action('wp_ajax_user_register_ajax', 'user_register_ajax');

If the user is not registered on the site he should get an email from getResponse mailing system with an OTP which the user will enter on the site and then he will get registered. Currently I’ve entered my email in the receiver’s email for testing purpose.

I’m stuck in the mailing part.

I had this code from Send mail using send grid api key and Pass Email and Name to GetResponse via API

I want to send an email from getResponse mailing system.

But so far this is all I got and can’t see the mistake in my code can anyone help me.

I am new to php can you help me solve this example [closed]

enter code here

can you help me

The electricity company wants to know to which group the citizens belong, based on their consumption and how much money they should pay at the end of the month.

Because of that the electricity company decided to reach out to you and asked you to write a program that finds which group a specific citizen belongs to.

Here are some information that will help you to decide which group a citizen belongs to:

Citizens groups
Group 1: 1 to 300 Kilowatt/hour, cost = 0.5$ for each Kilo.
Group 2: 300 to 600 Kilowatt/hour, cost = 1$ for each Kilo.``
Group 3: more than 600 Kilowatt/hour, cost = 2$ for each Kilo.
To calculate the cost in one month:
Use a variable called electricityConsumption.`enter code here`
In the variable add a value you want your program to check (this value in this variable is how much Kilowatts have been consumed in a single month).
At the end print to which group the citizen belongs to and how much his/her consumption cost.emphasized text

Session files are increasing fast in laravel

I have around 1000 users(website+application), the session files in framework folder are increasing rapidly, after sometime they are so much that godaddy’s limit is exhausted, my session lifetime is 525600, Can anyone help that how i will manage this.

Call to undefined function imap_open()

I’m trying to IMAP working on my Mac running Big Sur.

I used HomeBrew to install PHP 8.1:

brew tap shivammathur/php
brew tap shivammathur/extensions
brew install [email protected]

PHP is working and according to the phpinfo() it’s using the correct path.
There’s also the additional path to the imap.ini
The path in the imap.ini exists and there is a imap.so

When i run “php -m” imap is mentioned in the list.

But when I run my code I get the error:

Call to undefined function imap_open()

I tried reinstalling the php with extensions and I tried https://stackoverflow.com/a/66047249/909723 but no success

Hope someone can help!

Thanks in advance