這裏是我當前的代碼:使用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」查詢尤其不會造成麻煩。 –