【问题标题】:Inserting values from PHP array into DB将 PHP 数组中的值插入数据库
【发布时间】:2019-03-09 05:30:15
【问题描述】:

我有一个带有产品 ID 的 PHP 数组 p_ids(购物车)。我最后插入了订单 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";
}
?>

【问题讨论】:

  • 你的代码对SQL注入很开放,请学习使用参数化查询而不是替换变量。
  • 是的,我现在,我需要学习它,谢谢:) 你有什么好的文章,你可以推荐什么?
  • 您没有在右侧的相关链接中看到最重要的问题吗? stackoverflow.com/questions/60174/…

标签: php mysql arrays database insert


【解决方案1】:

使用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);
}

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2014-08-24
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2014-07-21
    • 2015-12-03
    • 2014-12-30
    相关资源
    最近更新 更多