且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

php pdo 多数组插入

更新时间:2023-01-30 17:13:54

利用 MySQL 中多次插入的插入速度(http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html ),你可以使用准备好的语句构建更大的查询.这确实增加了迭代方法的复杂性,因此可能只对高需求系统或大型数据集值得.

To take advantage of the insert speed of multiple inserts in MySQL ( http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html ), you can use a prepared statement that builds the larger query. This does add complexity over an more iterative approach, so is probably only worth it for high-demand systems or largish data sets.

如果您有上述建议的数据:

If you have your data as you proposed above:

$person = array(array('name'=>'Dan', 'age'=>'30'), array('name' =>
'John', 'age' => '25'), array('name' => 'Wendy', 'age' => '32'));

我们希望生成如下所示的查询:

We're looking to generate a query that looks something like this:

insert into table (name, age) values (?,?), (?,?), (?,?);

要将这些整合在一起,您需要一些与此完全不同的东西:

To pull this together you'll want something not totally unlike this:

$pdo->beginTransaction() // also helps speed up your inserts
$insert_values = array();
foreach($person as $p){
   $question_marks[] = '(?,?)';
   $insert_values = array_merge($insert_values, array_values($p));
}

$sql = "INSERT INTO table_name (name, age) VALUES " . implode(',', $question_marks);

$stmt = $pdo->prepare ($sql);
try {
    $stmt->execute($insert_values);
} catch (PDOException $e){
    // Do something smart about it...
}
$pdo->commit();