【问题标题】:(PDO PHP) The fastest way to update or insert multiple rows?(PDO PHP) 更新或插入多行的最快方法?
【发布时间】:2014-11-16 17:19:09
【问题描述】:

我不知道如何使用 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();

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

是否有另一种方法可以安全地批量更新或向数据库插入多行?感谢您的帮助。

对不起我的英语。

【问题讨论】:

    标签: php pdo


    【解决方案1】:

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

    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 请给我们看
    猜你喜欢
    • 1970-01-01
    • 2012-06-27
    • 2014-12-14
    • 2019-12-02
    • 2016-02-06
    • 2021-10-30
    • 2012-08-30
    • 2012-12-23
    相关资源
    最近更新 更多