如何将 PDO 的 execute($variable) 转换为 MySQLi 语句

How to convert PDO's execute($variable) to MySQLi statements

我正在学习使用 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 不正确。

MySQLi 比 PDO 更难。我强烈建议尽可能使用 PDO。

如果你想在 mysqli 中绑定未知数量的参数,你需要创建带有类型的字符串,然后展开数组。

$arrayKeys = array_keys($products_in_cart);
$stmt->bind_param(str_repeat("s", count($arrayKeys)), ...$arrayKeys);
$stmt->execute();