问题描述
我目前在 MySQL 上使用这种类型的 SQL 在一个查询中插入多行值:
I am currently using this type of SQL on MySQL to insert multiple rows of values in one single query:
INSERT INTO `tbl` (`key1`,`key2`) VALUES ('r1v1','r1v2'),('r2v1','r2v2'),...
关于 PDO 的阅读,使用准备好的语句应该比静态查询给我更好的安全性.
On the readings on PDO, the use prepared statements should give me a better security than static queries.
因此,我想知道是否可以使用准备好的语句生成通过使用一个查询插入多行值".
I would therefore like to know whether it is possible to generate "inserting multiple rows of values by the use of one query" using prepared statements.
如果是,我可以知道如何实施吗?
If yes, may I know how can I implement it?
推荐答案
使用 PDO 准备好的语句插入多值
在一个执行语句中插入多个值.为什么是因为根据这个页面它比常规更快插入.
Inserting multiple values in one execute statement. Why because according to this page it is faster than regular inserts.
$datafields = array('fielda', 'fieldb', ... );
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
更多数据值,或者您可能有一个填充数据的循环.
more data values or you probably have a loop that populates data.
对于准备好的插入,您需要知道要插入的字段,以及创建 ?用于绑定参数的占位符.
With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.
insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
这基本上就是我们希望插入语句的样子.
That is basically how we want the insert statement to look like.
现在,代码:
function placeholders($text, $count=0, $separator=","){
$result = array();
if($count > 0){
for($x=0; $x<$count; $x++){
$result[] = $text;
}
}
return implode($separator, $result);
}
$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
$question_marks[] = '(' . placeholders('?', sizeof($d)) . ')';
$insert_values = array_merge($insert_values, array_values($d));
}
$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " .
implode(',', $question_marks);
$stmt = $pdo->prepare ($sql);
$stmt->execute($insert_values);
$pdo->commit();
尽管在我的测试中,使用多个插入和常规准备插入的单个值时只有 1 秒的差异.
Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.
这篇关于PDO Prepared 在单个查询中插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!