-1

I have a PHP array p_ids (shopping cart) with products id. I have last inserted order id. I need insert all products from cart into DB. Everithing work fine, i just cant insert data from array. There willbe alwais the same order id, but differrent product id from array.

<?php

 include "connect.php";
 $conn = $_SESSION['connection'];

 $p_ids = array();
 $p_ids = $_SESSION['cart'];
 $name = $_REQUEST["name"];
 $surname = $_REQUEST["surname"];
 $email = $_REQUEST["email"];
 $street = $_REQUEST["street"];
 $city = $_REQUEST["city"];
 $psc = $_REQUEST["psc"];
 $phone = $_REQUEST["phone"];

 $sql0 = mysqli_query($conn, "SELECT * FROM products WHERE id IN (" . implode(',', array_map('intval', $p_ids)) . ") AND ordered=1") or die(mysqli_error());

 $check = mysqli_num_rows($sql0);

 if ($check > 0) {
echo "0";
 } else {

$sql1 = "INSERT INTO orders VALUES ('', '$name', '$surname', '$email', '$phone', '$street', '$city', '$psc', CURRENT_TIMESTAMP, '', '', '', '')";

if (mysqli_query($conn, $sql1)) {
    $last_id = mysqli_insert_id($conn);

    $sql2 = mysqli_query($conn, "UPDATE products SET ordered=1 WHERE id IN (" . implode(',', array_map('intval', $p_ids)) . ")") or die(mysqli_error());


    for ($i = 0; $i <= count($p_ids); $i++){
        there i need insert arrray into DB
    }


    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql1 . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);

echo "1";
}
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
k4znIm
  • 65
  • 1
  • 1
  • 7
  • 1
    Your code is wide open to SQL injection, please learn to use parametrized queries instead of substituting variables. – Barmar Oct 03 '18 at 22:08
  • Yes i now, i need to learn it, thank you :) do you have some good articles about it, what you can recomend? – k4znIm Oct 04 '18 at 07:22
  • Don't you see the top question in the **Related** links on the right side? https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Barmar Oct 04 '18 at 15:21

1 Answers1

2

Use a foreach loop to insert each product ID into the table.

$stmt = mysqli_prepare($conn, "INSERT INTO order_products (order_id, product_id) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ii", $last_id, $product_id);
foreach ($p_ids as $product_id) {
    mysqli_stmt_execute($stmt);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612