这里是我当前的代码:使用PHP插入数组到MySQL数据库?
// 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",
}
我如何让它循环并插入所有的行?还有,以相反的顺序插入它们的方法(从最后一个开始,到第一个结束)?
任何帮助,将不胜感激:)
你忘了正确格式化你的SQL。这将导致广泛的不良结果 - 从语法错误到sql注入。然而,“truncate table”查询尤其不会造成麻烦。 –