(PDO PHP)更新或插入多行的最快方法?

use*_*314 0 php pdo

我不知道如何使用PDO更新或插入多行.请帮我.

我脑子里想的是:

$stmt = $dbh->query("update_line_1; update_line_2; update_line_3");
//update_line_1: update table a set a.column1 = "s1" where a.id = 1
//update_line_2: update table a set a.column1 = "s2" where a.id = 2
//....

$stm = $dbh->query("insert_line_1; insert_line_3; insert_line_3");
//something is like the update line above.
Run Code Online (Sandbox Code Playgroud)

我不知道这种方式是否有效.如果您有其他方式,请告诉我.非常感谢你.

如果我使用prepare语句,我每次只更新每一行.(这比上面安全得多)

$stmt = $dbh->prepare("update table a set a.colum1 = :column1 where a.id = :id");
$stmt->bindParam(":column1","s1");
$stmt->bindparam(":id",1);
$stmt->execute();
Run Code Online (Sandbox Code Playgroud)

我不想做的最讨厌的事情是使用循环遍历数组中的所有元素,并且每次更新或插入每个元素

是另一种批量安全地更新或向数据库插入多行的方法吗?谢谢您帮忙.

抱歉我的英文.

Mik*_*ant 8

对于插入,您可以使用以下语法插入多行数据:

INSERT INTO table (col1, col2, col3)
VALUES
    ('1', '2', '3'),
    ('a', 'b', 'c'),
    ('foo', 'bar', 'baz')
Run Code Online (Sandbox Code Playgroud)

对于更新,默认情况下,更新将生成符合查询条件的行数.所以这样的事情会更新整个表格

UPDATE table SET col = 'a'
Run Code Online (Sandbox Code Playgroud)

如果您尝试更新每行的不同值,除了对每个操作执行查询之外,您实际上没有太多选择.不过我会建议你在PDO示例的基础上做一下这样的事情:

$update_array = array(
    1 => 'foo',
    2 => 'bar',
    10 => 'baz'
); // key is row id, value is value to be updated

$stmt = $dbh->prepare("UPDATE table SET column1 = :column1 where id = :id");
$stmt->bindParam(":column1",$column_value);
$stmt->bindparam(":id",$id);
foreach($update_array as $k => $v) {
    $id = $k
    $column_value = $v;
    $stmt->execute();
    // add error handling here
}
Run Code Online (Sandbox Code Playgroud)

使用此方法,您至少可以利用预准备语句来最小化查询开销.

  • @ user3883314可以添加问题的答案.在这种情况下,您可能希望这样做,以便人们可以有多种选择. (2认同)