2016-10-02 122 views
1

這裏是我當前的代碼:使用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", 
} 

我如何讓它循環並插入所有的行?還有,以相反的順序插入它們的方法(從最後一個開始,到第一個結束)?

任何幫助,將不勝感激:)

回答

4
  • 要遍歷數組,您必須使用foreach運算符。
  • 要執行多個插入,你必須使用準備好的發言

因此,儘管在所有其他匆忙書面答覆什麼表示,代碼應該是

$stmt = $con->prepare("INSERT INTO `table` (`id`, `name`, `status`) VALUES (?,?,?)"); 
$stmt->bind_param("sss", $id, $name, $status); 
foreach ($data as $row) 
{ 
    $id = $row['id']; 
    $name = $row['name']; 
    $status = $row['status']; 
    $stmt->execute(); 
} 
-1

隨着foreach循環:

foreach($data as $index => $row){ 
    $insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('". $row['id'] ."', '". $row['name'] ."', '". $row['status'] ."');"); 
} 

但是請注意,插入從不受信任來源的任何數據時,你就要小心了,因爲它讓你容易受到SQL注入。瞭解更多關於SQL注入的信息:How can I prevent SQL injection in PHP?

-1

您應該使用MySql多行插入。

INSERT INTO tbl_name (col1,col2) VALUES(1,2), (3,4); 

MySQL的插入參考: http://dev.mysql.com/doc/refman/5.7/en/insert.html

在PHP中,你會做這樣的事情(修改代碼)

// 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); 

$query = "INSERT INTO `table` (`id`, `name`, `status`) VALUES "; 

foreach($data as $d) { 
$query .= "('".$d['id']."', '".$d['name']."', '".$d['status']."'),"; 
} 
// Query. Note the trim to remove the last , 
$insertstatement = mysqli_query($con, trim($query,','); 

您還可以繼續從對重複KEY閱讀... &上述其他有用的補充。您還應該確保您的數據正確轉義/來自100%安全的來源。如果狀態包含諸如「」; TRUNCATE TABLE ...「未轉義,您可能會遇到麻煩。

編輯:另外兩個解決方案也工作並插入所有行。然而,我的版本在一個查詢中插入了所有的行。根據數據的大小,運行 - 例如 - 1000查詢而不是一個查詢可能不太可行。

+0

你忘了正確格式化你的SQL。這將導致廣泛的不良結果 - 從語法錯誤到sql注入。然而,「truncate table」查詢尤其不會造成麻煩。 –

0

爲了插入多行數據或數組的數組,你必須迭代上的數組變量使用foreach(),這樣它會循環你單行,以便您可以執行m您想要執行的操作。

您可以使用mysqli.*PDO或使用prepared statements插入數據。您可以決定在哪種情況下插入數據。

的mysqli:

<?php 
$data = json_decode($jsondata, true); 
foreach($data as $single_data) 
{ 
$insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('".$single_data['id']."', '".$single_data['name']."', '".$single_data['status']."');"); 
} 
?> 

準備語句:

<?php 
$query = $con->prepare("INSERT INTO `table` (`id`, `name`, `status`) VALUES (?,?,?)"); 
$query->bind_param("sss", $id, $name, $status); 
foreach ($data as $row) 
{ 
    $id = $row['id']; 
    $name = $row['name']; 
    $status = $row['status']; 
    $result->execute();// This will execute the statement. 
} 
?> 

PDO與準備語句:

<?php 
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword); 
$statement = $link->prepare("INSERT INTO testtable(name, lastname, age) 
    VALUES(:id, :name, :status)"); 
foreach($data as $row) 
{ 
$statement->execute(array(
    "id" => $row['id'], 
    "name" => $row['name'], 
    "status" => $row['status'] 
)); 
} 
?> 

希望所以我的解釋對於更好地理解所有這三種類型的陳述都是很清楚的。