我正在學(xué)習(xí)使用 PDO 的教程,我必須使用 MySQLi。在教程中,有這一行:$stmt->execute(array_keys($products_in_cart));我最好的嘗試是這樣做:$stmt->bind_param('i', array_keys($products_in_cart));$stmt->execute();這有效,但僅適用于一種產(chǎn)品,即當(dāng)數(shù)組僅包含一個元素 ([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 cartif ($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']]; }}我相信當(dāng)有多個產(chǎn)品時,SQL 語句會因 IN() 子句而變得混亂,即$array_to_question_marks不正確。
1 回答

大話西游666
TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個贊
MySQLi 比 PDO 更難。我強(qiáng)烈建議盡可能使用 PDO。
如果你想在 mysqli 中綁定未知數(shù)量的參數(shù),你需要創(chuàng)建帶有類型的字符串,然后展開數(shù)組。
$arrayKeys = array_keys($products_in_cart);
$stmt->bind_param(str_repeat("s", count($arrayKeys)), ...$arrayKeys);
$stmt->execute();
- 1 回答
- 0 關(guān)注
- 92 瀏覽
添加回答
舉報
0/150
提交
取消