Как преобразовать команду PDO execute ($ variable) в операторы MySQLi - PullRequest
1 голос
/ 07 апреля 2020

Я следую руководству, в котором используется 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 не получает правильно.

1 Ответ

3 голосов
/ 07 апреля 2020

MySQLi сложнее, чем PDO. Я настоятельно рекомендую использовать PDO, когда это возможно.

Если вы хотите связать неизвестное количество параметров в mysqli, вам нужно создать строку с типами, а затем разделить массив.

$arrayKeys = array_keys($products_in_cart);
$stmt->bind_param(str_repeat("s", count($arrayKeys)), ...$arrayKeys);
$stmt->execute();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...