2013-03-11 120 views
1

我有一個JSON陣列,我轉換成產生一系列ID的諸如PHP數組:JSON/PHP陣列到MySQL插入

Array 
    (
     [0] => 2343 
     [1] => 4345 
     [2] => 4432 
     [3] => 3456 
    ) 

我想這些圖像ID插入到數據庫中與一個共同的畫廊ID - 這是它會如何看,如果我是單獨寫每個查詢:

$query1 = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('2343', '1')"; 
$query2 = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('4345', '1')"; 
$query3 = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('4432', '1')"; 
$query4 = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('3456', '1')"; 

如何將我莫名其妙地循環這使它作爲一種簡單高效的可能嗎?任何幫助將非常感激。

回答

5

試試這個

$sql = "INSERT INTO gallery_media (media_id, gallery_id) VALUES "; 
foreach($ids as $id) { 
    $sql .= "('$id', '1'),"; 
} 
$sql = rtrim($sql,","); 
+0

我花了一段時間才弄清楚你在這裏做什麼 - 但它像一個魅力,簡單。謝謝,nauphal。 – Chris 2013-03-11 07:45:25

1

陣列上只是循環。例:

foreach ($your_array as $item){ 
    $query = sprintf("INSERT INTO gallery_media (media_id, gallery_id) VALUES (%d,1)",$item); 
    //Now execute query 
} 
1

簡單

foreach ($id_array as $id) { 
    $query = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('$id', '1')"; 
    // execute your query 
} 
1

試試這個:

foreach((array) $data_arr as $key => $value) 
{ 
$query = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('$value', '1')"; 
} 
2

它的時間使用準備好的語句!

$pdo = new \PDO('...'); 
$sth = $pdo->prepare("INSERT INTO gallery_media (media_id, gallery_id) VALUES (?, '1')"); 
foreach ($data_array as $value) 
    $sth->execute(array($value)); 
1

我認爲最短的方法將使用implode func一次創建整個查詢。嘗試這樣的:$query = "INSERT INTO gallery_media (media_id, gallery_id) VALUES ('".implode("','1'),",$vals_array)."')";