gpt4 book ai didi

php - 如何解析嵌套的 json 并存储到 mysql 数据库中?

转载 作者:行者123 更新时间:2023-12-04 10:40:36 24 4
gpt4 key购买 nike

我不知道 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后存储到数据库中?

最佳答案

使用循环插入您的 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;

关于php - 如何解析嵌套的 json 并存储到 mysql 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59949658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com