【发布时间】:2015-02-26 19:01:49
【问题描述】:
我有以下 json 文件,我通过我的移动应用程序将其发送到 PHP,在 PHP 端,我想对其进行解码并将其插入到 mysql 数据库中。
[{"Address":"Somewhere ",
"Area":"Somwhe",
"CreatedBy":null,
"CreatedDate":"\/Date(1419786831365+0530)\/",
"Distance":0,
"EditedDate":"\/Date(-62135596800000+0000)\/",
"Latitude":12.903999947011471,
"Longitude":77.607999974861741,
"Phone1":"80372899",
"Phone2":"993729927",
"Response":null,
"StoreDescriptions":[],
"StoreName":"First"},
{"Address":"Addwmsj",
"Area":"Sbnns",
"CreatedBy":null,
"CreatedDate":"\/Date(1419786863657+0530)\/",
"Distance":0,
"EditedDate":"\/Date(-62135596800000+0000)\/",
"Latitude":12.960867136716843,
"Longitude":77.647689711302519,
"Phone1":"799268299",
"Phone2":"68393973738",
"Response":"Waiting",
"StoreDescriptions":[{"LongNBQuantity":862,
"MeetDate":"\/Date(1419786915048+0530)\/",
"MeetSummary":"Meeting",
"Response":"Negative",
"StoreName":"Ssxond",
"id":1
},
{"LongNBQuantity":8862,
"MeetDate":"\/Date(1419786927673+0530)\/",
"MeetSummary":"Pjsjsbsj",
"Response":"Waiting",
"StoreName":"Ssxond",
"id":2}],
"StoreName":"Ssxond"},
{"Address":"Sumwhere",
"Area":"Righthere",
"CreatedBy":null,
"CreatedDate":"\/Date(1419953186686+0530)\/",
"Distance":0,
"EditedDate":"\/Date(-62135596800000+0000)\/",
"Latitude":12.903999947011471,
"Longitude":77.607999974861741,
"Phone1":"872737288",
"Phone2":"663838828",
"Response":null,
"StoreDescriptions":[],
"StoreName":"NewEntry"}]
正如我们在此看到的,我有对象数组 [{},{},{}...{}],当其中一个对象具有像 {"abc":"bcd 这样的对象数组时,复杂性会增加","storedesc":[{},{},{},....{}]} ,因此与简单的 json 相比,这有点复杂。
我的代码不起作用。任何人都可以指导我正确的方向。谢谢
$json = file_get_contents('php://input');
$result = json_decode($json,true);
/*
Database connection setup done here.
*/
foreach ($result as $key => $value) {
if($value){
$sql = "INSERT INTO StoreInfo(name,created_date,edited_date,address,area,ph_num1,ph_num2,response,latitude,longitude) VALUES ($value->StoreName,$value->CreatedDate,'hellyeah',$value->Address,$value->Area,$value->Phone1,$value->Phone2,$value->Response,$value->Longitude,$value->Latitude)";
if($conn->query($sql) === TRUE){
echo "New record inserted";
}
}
}
【问题讨论】:
-
1) 考虑为您的 SQL 使用准备好的语句和 2) 因为您的 JSON 具有嵌套结构,您将需要多个具有某种连接键的数据库表。
-
什么是“不工作”?那是什么意思? “不工作”没有任何的含义。你看到任何错误吗?是否有任何记录插入到数据库中?你的电脑突然死机了吗?无论如何,让我们尝试一些调试。您是否尝试
echo $sql来查看您尝试运行的查询是什么?此外,不要只是假设查询有效。使用错误检查!添加else{ die($conn->error); }。 -
@Mr.Llama 我正在使用 3 个表,但首先我想将它插入到 1 个表中。