我要将这个多维数组插入mysql数据库:
{
customer_id: "25",
total: 238000,
firstname: "oci",
product: [
{
product_id: "6",
product_name: "Orange"
},
{
product_id: "5",
product_name: "Melon"
}
]
}
这是我的代码
$_POST = json_decode(file_get_contents('php://input'), true);
$customer_id= $_POST['customer_id'];
$total= $_POST['total'];
$firstname= $_POST['firstname'];
foreach ($_POST['product'] as $q_product => $v) {
$product_id = $v['product_id'];
$product_name= $v['product_name'];
$query = "INSERT INTO tbl_order
(order_id,customer_id,total,firstname) VALUES (NULL,'$customer_id','$total','$firstname')";
$queryy = "INSERT INTO tbl_order_product
(order_id,product_id,product_name) VALUES (LAST_INSERT_ID(),$product_id,'$product_name')";
}
$result = mysqli_query($link, $query);
$resultt = mysqli_query($link, $queryy);
我不能将“queryy”插入到tbl_order_product中,只能将“queryy”插入到tbl_order_product表中。请帮助我将“product”数组也插入到tbl_order_product表中。
对您的问题进行简单的更新以使其工作(不包括sql注入防止)
foreach ($_POST['product'] as $q_product => $v) {
$product_id = $v['product_id'];
$product_name = $v['product_name'];
$query = "INSERT INTO tbl_order (order_id,customer_id,total,firstname)
VALUES (NULL,'$customer_id','$total','$firstname')";
$result = mysqli_query($link, $query);
$last_id = mysqli_insert_id($link);
$queryy = "INSERT INTO tbl_order_product (order_id,product_id,product_name)
VALUES ($last_id ,$product_id,'$product_name')";
$resultt = mysqli_query($link, $queryy);
}
要使用prepared语句来防止sql注入,请看一下这些。