Php 如何解析嵌套的json并将其存储到mysql数据库中?
我对PHP一无所知,有人能帮我如何将嵌套的JSON数据存储到数据库中吗?我编写代码,但每次只针对一行,但如果我想解析嵌套的JSON,我该怎么做Php 如何解析嵌套的json并将其存储到mysql数据库中?,php,mysql,json,Php,Mysql,Json,我对PHP一无所知,有人能帮我如何将嵌套的JSON数据存储到数据库中吗?我编写代码,但每次只针对一行,但如果我想解析嵌套的JSON,我该怎么做 [ { "product_name": "Product3", "product_price": "500", "product_quantity": "5", "userid": "1", "orderid": "1" }, {
[
{
"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"
}
]
我试图插入使用邮递员,但只有一个空白行插入。请帮助我如何在命中API后将其存储到数据库中?使用循环插入json值。我还没有测试过,但我认为它对你有用
// 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);
foreach($obj as $product) :
$productid = $product['product_id'];
$productname = $product['product_name'];
$productprice = $product['product_price'];
$productquantity = $product['product_quantity'];
$userid = $product['userid'];
$orderid = $product['orderid'];
if(!empty($productid)) :
$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';
}
endif;
endforeach;
添加一个循环,并对该循环中的单个对象执行当前正在执行的操作…
// 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);
foreach($obj as $product) :
$productid = $product['product_id'];
$productname = $product['product_name'];
$productprice = $product['product_price'];
$productquantity = $product['product_quantity'];
$userid = $product['userid'];
$orderid = $product['orderid'];
if(!empty($productid)) :
$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';
}
endif;
endforeach;