亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 PDO 的 execute($variable) 轉換為 MySQLi 語句

如何將 PDO 的 execute($variable) 轉換為 MySQLi 語句

PHP
慕勒3428872 2022-12-11 09:38:33
我正在學習使用 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 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']];    }}我相信當有多個產品時,SQL 語句會因 IN() 子句而變得混亂,即$array_to_question_marks不正確。
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

MySQLi 比 PDO 更難。我強烈建議盡可能使用 PDO。


如果你想在 mysqli 中綁定未知數量的參數,你需要創建帶有類型的字符串,然后展開數組。


$arrayKeys = array_keys($products_in_cart);

$stmt->bind_param(str_repeat("s", count($arrayKeys)), ...$arrayKeys);

$stmt->execute();


查看完整回答
反對 回復 2022-12-11
  • 1 回答
  • 0 關注
  • 94 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號