【发布时间】:2020-01-28 13:17:01
【问题描述】:
我对 PHP 一无所知,谁能帮助我如何将嵌套的 JSON 数据存储到数据库中?我编写代码,但一次只写一行,但如果我想解析嵌套的 JSON,我该怎么办?
[
{
"product_name": "Product3",
"product_price": "500",
"product_quantity": "5",
"userid": "1",
"orderid": "1"
},
{
"product_name": "Product4",
"product_price": "500",
"product_quantity": "5",
"userid": "1",
"orderid": "1"
},
{
"product_name": "Product5",
"product_price": "500",
"product_quantity": "5",
"userid": "1",
"orderid": "1"
}
]
// Creating MySQL connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Storing the received JSON in $json.
$json = file_get_contents('php://input');
// Decode the received JSON and store into $obj
$obj = json_decode($json,true);
$productid = $obj['product_id'];
$productname = $obj['product_name'];
$productprice = $obj['product_price'];
$productquantity = $obj['product_quantity'];
$userid = $obj['userid'];
$orderid = $obj['orderid'];
$query = "INSERT INTO order_product (product_id, product_name, product_price, product_quantity, userid, orderid) VALUES ('$productid','$productname','$productprice','$productquantity','$userid','$orderid')";
if(mysqli_query($con,$query)){
// On query success it will print below message.
$MSG = 'Data Successfully Submitted.' ;
// Converting the message into JSON format.
$json = json_encode($MSG);
// Echo the message.
echo $json ;
}
else{
echo 'Try Again';
}
我正在尝试使用 Postman 插入,但只插入了一个空白行。请帮助我在命中API后如何存储到数据库中?
【问题讨论】:
-
添加一个循环,并为该循环内的单个对象执行您当前正在执行的操作……