gpt4 book ai didi

php - 将json中的数据从php插入到mysql表中

转载 作者:行者123 更新时间:2023-11-29 06:15:28 25 4
gpt4 key购买 nike

我正在尝试将数据从 json 文件插入到表中,但行变为 0。不是来自 json 的值

DB

JSON 代码:

{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
}]
}

$connection = mysql_connect("localhost", "***", "!*****!");
if (!$connection)
{
die('PHP Mysql database connection could not connect : ' . mysql_error());
}
$db_selected = mysql_select_db("*****", $connection);


$result=mysql_query("SELECT * FROM $tbl_name wHERE ad_IMEI=ad_IMEI ");
$i=0;
while($row=mysql_fetch_array($result)) {
$response[$i]['dr_DeviceID'] = $row['ad_IDDevice'];
$response[$i]['dr_UserLocalLat']= $row['user_location_lat'];
$response[$i]['dr_UserLocalLong']= $row['user_location_long'];
$data['posts'][$i] = $response[$i];
$i=$i+2;}
$json_string = json_encode($data);
$file = 'select.json';
file_put_contents($file, $json_string);

$jsondata = file_get_contents('select.json');
$obj = json_decode($jsondata, true);
$id = $obj['posts']['dr_DeviceID'];
$dr_UserLocalLat = $obj['posts']['dr_UserLocalLat'];
$dr_UserLocalLong = $obj['posts']['dr_UserLocalLong'];
$sqlj = "INSERT INTO $tbl_name1 (dr_DeviceID, dr_UserLocalLat, dr_UserLocalLong) VALUES('$dr_DeviceID', '$dr_UserLocalLat', '$dr_UserLocalLong')";
$result=mysql_query($sqlj,$connection);

最佳答案

问题是您试图访问一组对象,就好像它是单个对象一样。这条线在这里 $data['posts'][$i] = $response[$i];您将一个项目添加到 $data['posts'] 数组。如果您的结果不止一行,您在上面留下的 json 示例将是

{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
},
{
"dr_DeviceID": "324",
"dr_UserLocalLat": "39.7482572",
"dr_UserLocalLong": " -19.1847516"
}]
}

因此,当您之后对 json 进行解码时,您会得到一个对象数组。要访问数组中的每个项目,您需要一些循环。否则,要从 json 中获取第一项,您需要执行
$obj['posts'][0]['dr_UserLocalLat'],而不是 $obj['posts']['dr_UserLocalLat']

关于php - 将json中的数据从php插入到mysql表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136597/

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