我正在学习使用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']];
}
}
我相信当有几种产品时,即IN()子句会弄乱SQL语句,即$array_to_question_marks
不合适。
MySQLi比PDO困难。我强烈建议尽可能使用PDO。
如果要在mysqli中绑定未知数量的参数,则需要创建带有类型的字符串,然后对数组进行splat处理。
$arrayKeys = array_keys($products_in_cart);
$stmt->bind_param(str_repeat("s", count($arrayKeys)), ...$arrayKeys);
$stmt->execute();
PDO和MySQLi不会在准备好的语句上共享行为。您应该阅读特定的MySQLi教程以实现您想要做的事情...