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

(PDO PHP)更新或插入多行的最快方法?,php,pdo,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 //.... $s

我不知道如何使用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.
我不知道这样行不行。如果你有别的办法,请告诉我。非常感谢你

如果我使用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();
是否有另一种方法可以安全地批量更新或向数据库插入多行?谢谢你的帮助


对不起,我的英语不好。

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

INSERT INTO table (col1, col2, col3)
VALUES
    ('1', '2', '3'),
    ('a', 'b', 'c'),
    ('foo', 'bar', 'baz')
对于更新,默认情况下,更新将影响满足查询条件的行数。所以像这样的东西会更新整个表

UPDATE table SET col = 'a'
如果您试图为每一行更新不同的值,那么除了为每个操作执行查询之外,您实际上没有太多选择。然而,我建议,在您的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
}

使用这种方法,您至少可以利用预先准备好的语句来最小化查询开销。

希望有更好的答案。@user3883314您希望有什么更好的答案?无法使用不同的WHERE条件批量更新您试图针对的多行。这个功能根本不存在。我找到了另一种使用PDO批量更新多行的方法。这就是我想要的。@user3883314对您的问题添加一个答案是可以接受的。在这种情况下,您可能希望这样做,这样人们就可以有多个选项。@user3883314请告诉我们