Sql Insert into Select语句PDO

时间:2016-10-12 01:31:55

标签: php mysql sql pdo

我试图在$userId语句中绑定$_SESSION存储的insert select值,但这似乎是错误的。

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]); 
    }

}

1 个答案:

答案 0 :(得分:0)

当你使用命名参数时,你应该在传递给执行函数的数组中使用该名称(而且 - 不确定为什么你有// ...。(在//:user_id//中)。< / p>

检查一下:

$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]);