2015-01-12 61 views
2

假設我有三行需要爲每個ID插入。用Msql多次插入三行

ID - FOO - BAR 
0  test1  something 
0  test2  something 
0  test3  something 

12  test1  something 
12  test2  something 
12  test3  something 

34  test1  something 
34  test2  something 
34  test3  something 

這裏是我當前的代碼

<?php 

$connection = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); 

$sql = "INSERT INTO books (id,foo,bar) VALUES (?,?,?)"; 

$statement = $connection->prepare("$sql"); 

$statement->execute(array("1", "test1", "something")); 

此刻,我只能夠一次插入1列,每一次更新執行數組中的值。是否可以循環插入,而使用某種數組插入所有的值?

+0

當然它的可能。你爲什麼不嘗試它? – developerwjk

+0

我做了,失敗了。 – ProEvilz

+0

那麼,我真正的意思是在你試過的地方發佈代碼。 – developerwjk

回答

0

我建議使用一個簡單的準備語句值綁定,就像這樣:

// array with data you want to insert 
$books = array(
    0 => array('id' => 1, 'foo' => 'somefoo1', 'bar' => 'somebar1'), 
    1 => array('id' => 2, 'foo' => 'somefoo2', 'bar' => 'somebar2'), 
); 

// create PDO connection 
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); 

// create a prepared SQL statement (for multiple executions) 
$stmt = $pdo->prepare('INSERT INTO books (id,foo,bar) VALUES (:id,:foo,:bar)'); 

// iterate over your data, bind the new values to the prepared statement 
// finally execute = insert 
foreach($books as $book) 
{ 
    $stmt->bindValue(':id', $book['id']); 
    $stmt->bindValue(':foo', $bookm['foo']); 
    $stmt->bindValue(':bar', $book['bar']); 
    $stmt->execute(); 
}