PDO 并在插入期间绑定多个值集 - 最近 [英] PDO and binding multiple value sets during insert - recently
问题描述
在 PHP 中使用 PDO,当必须一次将多行插入到表中时,我使用的 sql 如下所示:
Using PDO in PHP, when having to insert multiple rows into a table at once, I've used sql that looks something like this:
INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce');
如您所见,我在一条语句中插入了三行.我这样做的原因是我相信它比执行三个不同的语句来插入行更有效.
As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.
所以我的问题是:如果我希望能够像在单个语句中那样将我的值绑定到语句,我该如何在 PHP 中执行此操作:
So my question is this: how do I do this in PHP if I want to be able to bind my values to a statement like I do in single statement:
$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
"firstname"=>$firstName,
"lastName"=>$lastName));
所以我的问题是:有没有办法在多插入语句中进行绑定?类似的东西:
So my question is: Is there any way to bind in a multi-insert statement? Something like:
INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
推荐答案
只需使用 ?
占位符创建您的查询文本:
Just create your query text wtih ?
placeholders as:
INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)
并执行它.示例代码可以是:
And execute it. Sample code can be:
$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)']; // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);
这篇关于PDO 并在插入期间绑定多个值集 - 最近的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!