1

I'm following a tutorial which uses PDO and I must use MySQLi. In the tutorial, there is this line:

$stmt->execute(array_keys($products_in_cart));

and my best try is to do like this:

$stmt->bind_param('i', array_keys($products_in_cart));
$stmt->execute();

This works, but only with one product, i.e. when array contains only one element ([0] => 1).

Here is the whole part:

// 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']];
    }
}

I believe the SQL statement gets messed up for the IN() clause when there are several products, i.e. $array_to_question_marks does not get right.

Dharman
  • 30,962
  • 25
  • 85
  • 135

1 Answers1

3

MySQLi is more difficult than PDO. I strongly recommend using PDO whenever possible.

If you want to bind an unknown numbers of parameters in mysqli, you need to create string with types and then splat the array.

$arrayKeys = array_keys($products_in_cart);
$stmt->bind_param(str_repeat("s", count($arrayKeys)), ...$arrayKeys);
$stmt->execute();
Dharman
  • 30,962
  • 25
  • 85
  • 135