我们说我需要为每个ID插入三行。
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 :(得分: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();
}