I am trying to insert a JSON array into my MySQL database. Here is the format of the array:
${
"customer_id": "1",
"products":[ {
"product_id": "1",
"product_qty": "2"
}, {
"product_id": "2",
"product_qty": "4"
}, {
"product_id": "3",
"product_qty": "12"
}, {
"product_id": "4",
"product_qty": "22"
}],
"order_totalamount": "100"
}
I tried inserting the query as below:
<?php
require("config.inc.php");
$jsondata = file_get_contents('OrderFormat.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$cus_id = $data['customer_id'];
$product_id = $data['products']['product_id'];
$product_qty = $data['products']['product_qty'];
$order_totalamount = $data['order_totalamount'];
//insert into mysql table
$sql = "insert into `order`(cm_id,product_id,product_quantity,order_totalamount,order_id,order_date) values ($cus_id,$product_id,$product_qty,$order_totalamount,$cus_id,CURDATE())";
echo $sql;
//$sql1 = mysql_query($sql);
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysql_error());
}
?>
Also I decode the JSON data, and foreach loop.
Kindly help me in this issue.
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…