Best way to make multiple update with PDO

I need to update my table with multiple request.
With a form, i get some values that i will take for update my table.

  $products =  [
    'prodotto1' => [
      'referenza' => $_POST['referenza1'],
      'prezzo' => $_POST['prezzo1'],
    ],
    'prodotto2' => [
      'referenza' => $_POST['referenza2'],
      'prezzo' => $_POST['prezzo2'],
    ],
    'prodotto3' => [
      'referenza' => $_POST['referenza3'],
      'prezzo' => $_POST['prezzo3'],
    ]
  ];

I thought to do this with a foreach :

function updateProducts(array $params){
$pdo = $GLOBALS["db"];
$sql = "UPDATE product SET REFERENCE=:reference, PRICE=:price WHERE REFERENCE=:reference";
$stmt= $pdo->prepare($sql);

foreach ($params as $prodotto ){
    if ($prodotto['referenza'] && $prodotto['prezzo'] ){
        $stmt->bindParam(':reference', $prodotto['referenza'], PDO::PARAM_STR);
        $stmt->bindParam(':price', $prodotto['prezzo']);
        $stmt->execute();

    }
}

}

But i’m not sure that is the best way to do this.

Can u suggest me some goods practice ?

Undefined variable in php while insert to mysql [duplicate]

I am getting this error that the variable is undefined when I actually set it to the value and no matter what kind of value I set even simple $user = 1 ; doesn’t work and I got error it is undefined

<?php 

session_start();

include ('get-user-data.php');

$user = array();

if(isset($_SESSION['userID'])){
    require ('connection.php');
    $userId = $_SESSION['userID'];


    function wantToRead() {
        $query = " INSERT INTO bookshelf (id, tittle, category, thumbnail) VALUES ('$userId', ' Book', 'read')";
    }
}
?>

So I hava a small online shop project :( Uncaught Error: Call to undefined function mysql_connect() can anyone help me connect to database [duplicate]

so I do everything same with the tutorial but it’s end up getting
Uncaught Error: Call to undefined function mysql_connect()

**But I someguy told I need to change to sqli instead **
I’m not good with coding but I have to do this small project by myself

and some other php file too.
I’ll have download link for you too work with please help 🙁

http://www.mediafire.com/file/2bmmao9ibbjpwzv/plaincart.rar/file
database file is in library

WordPress shortecode

I am using myCred on my site. Specially myCred transfer. There is an existing shortcode for this particular plugin.
[mycred_transfer pay_to=1]
where pay_to is the recipient wordpress user id. I can only manually add a user id. But so I need to manually create a shortcode for every created user and it is no go :D.
so therefore I created this function to gather user id of the current post.

// Shortcode to output custom PHP
function author_id( $atts ) {
   echo $user_id = get_the_author_meta( 'ID' );
}
add_shortcode( 'my_author_id', 'author_id');

and it works for the user ID. but do not know how to replace it “1” in [mycred_transfer pay_to=1]
because if I replace “1” with a shortcode it does not work.
Thanks for ideas

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).