将php数组中的值插入db

4sup72z8  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(314)

我有一个php数组p\u id(购物车)与产品id。我已经最后插入订单id。我需要插入从购物车到数据库的所有产品。一切工作正常,我只是不能插入数组中的数据。数组中的订单id相同,但产品id不同。

<?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";
}
?>
tpgth1q7

tpgth1q71#

使用 foreach 循环将每个产品id插入表中。

$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);
}

相关问题