我想創建一個解碼JSON數組並將其插入數據庫的PHP腳本。到目前爲止,我已經設法讓腳本插入數組中的第一行,沒有別的。PHP解碼JSON數組並插入到MYSQL數據庫
我需要添加什麼才能讓腳本插入數組中的所有行?
這裏的陣列,忽略 「清單」,我並不需要這些數據,但(這是相當大的): json 這裏的腳本:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$con = mysql_connect($servername, $username, $password);
//select db
$selected = mysql_select_db("ed",$con);
$json_obj = file_get_contents("stations.json");
//convert to stdclass object
$arr = json_decode($json_obj,true);
//store the element values into variables
$id = $arr[0]["id"];
$name = $arr[0]["name"];
$system_id = $arr[0]["system_id"];
$max_landing_pad_size = $arr[0]["max_landing_pad_size"];
$distance_to_star = $arr[0]["distance_to_star"];
$faction = $arr[0]["faction"];
$government = $arr[0]["government"];
$allegiance = $arr[0]["allegiance"];
$state = $arr[0]["state"];
$type = $arr[0]["type"];
$has_blackmarket = $arr[0]["has_blackmarket"];
$has_commodities = $arr[0]["has_commodities"];
$has_refuel = $arr[0]["has_refuel"];
$has_repair = $arr[0]["has_repair"];
$has_rearm = $arr[0]["has_rearm"];
$has_outfitting = $arr[0]["has_outfitting"];
$has_shipyard = $arr[0]["has_shipyard"];
//insert values into mysql database
$sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard)
VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')";
if(!mysql_query($sql,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
?>
如果它真的很大,你可以考慮另一種方法,首先創建一個查詢字符串,它可以讓你創建一個插入批處理,然後運行它。或創建一個文件,然後'加載數據本地infile'。這將是更快,而不是逐行循環行 – Ghost