IDごとに挿入する必要がある3つの行があるとします。
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行しか挿入できず、実行配列の値を毎回更新しています。なんらかの配列を使用してすべての値を挿入しながら、挿入をループすることは可能ですか?
次のように、値をバインドする簡単な準備済みステートメントを使用することをお勧めします。
// 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();
}