以下是我的当前代码:
我该如何让它循环遍历它们并插入所有行?此外,是否有一种方法可以倒序插入它们(从最后一个开始,以第一个结束)?
// connect to database
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
// get the json file
$jsondata = file_get_contents('http://www.example.com');
// convert json to php array
$data = json_decode($jsondata, true);
// assign each of the variables
$id = $data['0']['id'];
$name = $data['0']['name'];
$status = $data['0']['status'];
$insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('".$id."', '".$name."', '".$status."');");
技术上这段代码是有效的,但它只添加了第一个项目。
例如,这里是正在导入的原始json:
[
{
"id":"19839",
"status":"active",
"name":"First Name",
},
{
"id":"19840",
"status":"active",
"name":"Second Name",
},
{
"id":"19841",
"status":"active",
"name":"Another Name",
},
{
"id":"19842",
"status":"active",
"name":"Last Name",
}
]
我的代码只会将这个插入到数据库中:
{
"id":"19839",
"status":"active",
"name":"First Name",
}
我该如何让它循环遍历它们并插入所有行?此外,是否有一种方法可以倒序插入它们(从最后一个开始,以第一个结束)?