【问题标题】:How to convert PDO's execute($variable) to MySQLi statements如何将 PDO 的 execute($variable) 转换为 MySQLi 语句
【发布时间】:2020-07-19 11:36:27
【问题描述】:

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

【问题讨论】:

    标签: php mysqli pdo


    【解决方案1】:

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

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

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

    【讨论】:

    • PDO 难度并没有那么大,但方法基本上是要走的路。
    猜你喜欢
    • 2023-04-09
    • 2015-01-25
    • 1970-01-01
    • 2021-01-03
    • 2019-12-19
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多