Mostafa Esmat Mostafa Esmat - 1 month ago 7
SQL Question

Sql Insert Into Select statement PDO

I'm trying to bind

$userId
value stored from
$_SESSION
inside an
insert select
statement but it seems is so wrong.

class Cart {

public function addToCart($userId, $prodId) {

$sql = "INSERT INTO `cart` (prod_id, user_id, prod_title, prod_img,quantity, price)
SELECT product_id, //:user_id//, product_title, product_img, 1, product_price
FROM `products`
WHERE product_id = :product_id
";

$q = $this->_pdo->prepare($sql);
$q->execute([ 'user_id' => $userId , 'product_id' => $prodId]);
}

}

Answer

When you use named parameters you should use that name in the array you pass to the execute function (and also - not sure why you have the //...// (in the //:user_id//).

Check this:

$sql = "INSERT INTO `cart` (prod_id, user_id, prod_title, prod_img,quantity, price)
            SELECT product_id, :user_id, product_title, product_img, 1, product_price
            FROM  `products`
            WHERE  product_id = :product_id
    ";

$q = $this->_pdo->prepare($sql);
$q->execute([ ':user_id' => $userId , ':product_id' => $prodId]);