我正在学习使用 PDO 的教程,我必须使用 MySQLi。在教程中,有这一行:
$stmt->execute(array_keys($products_in_cart));
我最好的尝试是这样做:
$stmt->bind_param('i', array_keys($products_in_cart));
$stmt->execute();
这有效,但仅适用于一种产品,即当数组仅包含一个元素 ([0] => 1) 时。
这是整个部分:
// Check the session variable for products in cart
$products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : array();
$products = array();
$subtotal = 0.00;
// If there are products in cart
if ($products_in_cart) {
// There are products in the cart so we need to select those products from the database
// Products in cart array to question mark string array, we need the SQL statement to include IN (?,?,?,...etc)
$array_to_question_marks = implode(',', array_fill(0, count($products_in_cart), '?'));
$stmt = $mysqli->prepare('SELECT * FROM products WHERE id IN (' . $array_to_question_marks . ')');
// We only need the array keys, not the values, the keys are the id's of the products
$stmt->bind_param('i', array_keys($products_in_cart));
$stmt->execute();
// Fetch the products from the database and return the result as an Array
$products = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// Calculate the subtotal
foreach ($products as $product) {
$subtotal += (float) $product['price'] * (int) $products_in_cart[$product['id']];
}
}
我相信当有多个产品时,SQL 语句会因 IN() 子句而变得混乱,即$array_to_question_marks不正确。
大话西游666