gpt4 book ai didi

php - 尝试读取json并用php将其写入sql

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

我尝试从文件或url读取json,然后使用php将其写入sql

我编写了这段代码:

<?php
//connect to mysql db
$username = "test";
$password = "test";
$database = "wordpressdb";
$host = "localhost";

$conn = mysqli_connect($host, $username, $password, $database)
if($conn === false){
die("FAIL" . mysqli_connect_error());
}

//read the json file contents
$jsondata = file_get_contents('test.json');


//{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}




//convert json object to php associative array
$data = json_decode($jsondata, true);

//get the employee details




$cod = $data['cod'];
$calctime = $data['calctime'];
$cnt = $data['cnt'];
$id = $data['list']['id'];
$name = $data['list']['name'];
$lon = $data['list']['coord']['lon'];
$lat = $data['list']['coord']['lat'];
$temp = $data['list']['main']['temp'];
$min = $data['list']['main']['temp_min'];
$max = $data['list']['main']['temp_max'];
$pressure = $data['list']['main']['pressure'];
$level = $data['list']['main']['sea_level'];
$level2= $data['list']['main']['grnd_level'];
$humidity = $data['list']['main']['humidity'];
$dt = $data['list']['dt'];
$speed = $data['list']['wind']['speed'];
$deg = $data['list']['wind']['deg'];
$h = $data['list']['rain']['3h'];
$all = $data['list']['clouds']['all'];
$id2 = $data['list']['weather']['id'];
$main = $data['list']['weather']['main'];
$description = $data['list']['weather']['description'];
$icon = $data['list']['weather']['icon'];

//insert into mysql table
$sql = "INSERT INTO test(cod, calctime, cnt, id, name, lon, lat, temp, temp_min, temp_max, pressure, sea_level, grnd_level, humidity, dt, speed, deg, 3h, all, id, main, descriptio, icon)
VALUES('$cod', '$calctime', '$cnt', '$id', '$name', '$lon', '$lat', '$temp', '$min', '$max', '$pressure', '$level', '$level2', '$humidity', '$dt', '$speed', '$deg', '$h', '$deg', '$all', '$id2', '$main', '$description', '$icon')";
if(mysqli_query($link, $sql)){

echo "Records inserted successfully.";

} else{

echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);

}
?>

但是代码不起作用:(我是编程新手,我想知道如何制作这个(Json 到 php 到 mysql)。有人可以帮我修复代码吗?我正在尝试从 5 天开始修复它。

最佳答案

$link 未定义。在您的情况下,它应该是 $conn

关于php - 尝试读取json并用php将其写入sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774425/

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