我最近开始编写购物车类及其存储库(函数)的代码,我在INSERT INTO语句中遇到了SELECT语句的问题,问题是当我尝试执行此代码时它执行但是“SELECT语句总是在数据库中返回0“告知productPrice存在于数据库中,其值为
代码:
class ShoppingCartRepo
{
public function addToCart($productId, $cartId)
{
$dbh = mySqlDatabase::getConnectionObject();
$sql = "INSERT INTO cartitem (productId, cartId, singlePrice, quantity)
VALUES (:productId, :cartId, 'SELECT productPrice FROM products WHERE productId = :productId', 1)";
$stmt = $dbh->prepare($sql);
$data = array(
':productId' => $productId,
':cartId' => $cartId,
);
$stmt->execute($data);
return $dbh->lastInsertId();
}
}
答案 0 :(得分:2)
不要使用引号,你想要的是子查询:
$sql = "INSERT INTO cartitem (productId, cartId, singlePrice, quantity)
VALUES (:productId, :cartId, (SELECT productPrice FROM products WHERE productId = :productId), 1)";