代码之家  ›  专栏  ›  技术社区  ›  Nrc

PDO如何回复更新的数量

  •  0
  • Nrc  · 技术社区  · 10 年前

    我如何回复使用此代码更新了多少记录? 我知道我可以在常见更新中做到这一点:

    echo $stmt->rowCount() . " records UPDATED successfully"; 
    

    但这里的问题是,当同时有多个更新时,如何做到这一点。

    关于可能重复的注意事项:我已经解释了我的问题不同于: PDO were rows affected during execute statement 该解决方案仅用于一次更新,在本代码中不起作用。我问的是当有多个更新时如何计数。

    try {
        require_once 'connexion.php';
    
        $stmt = $conn->prepare("UPDATE bookmarks
                                SET podcast=:podcast, text=:text
                                WHERE id=:id");
        $stmt->bindParam(':podcast', $podcast);
        $stmt->bindParam(':text', $text);
        $stmt->bindParam(':id', $id);
    
        $podcast = 1;
        $text = "text 1";
        $id = 147;
        $stmt->execute();
    
        // another row:
        $podcast = 2;
        $text = "text 2";
        $id = 265;
        $stmt->execute();
    
        // echo " records UPDATED successfully";
    }
    
    catch(PDOException $e){
        echo $e->getMessage();
    }
    
    2 回复  |  直到 9 年前
        1
  •  1
  •   RiggsFolly    10 年前

    试试这个。

    当你做多个 ->execute() 你必须记录每个人的计数 ->执行() 然后在最后显示累计总数

    try {
        require_once 'connexion.php';
        $update_count = 0;
    
        $stmt = $conn->prepare("UPDATE bookmarks
                                SET podcast=:podcast, text=:text
                                WHERE id=:id");
        $stmt->bindParam(':podcast', $podcast);
        $stmt->bindParam(':text', $text);
        $stmt->bindParam(':id', $id);
    
        $podcast = 1;
        $text = "text 1";
        $id = 147;
        $stmt->execute();
    
        $update_count += $stmt->rowCount();
    
    
        // another row:
        $podcast = 2;
        $text = "text 2";
        $id = 265;
        $stmt->execute();
    
        $update_count += $stmt->rowCount();
    
    
        echo "$update_count records UPDATED successfully";
    }
    
    catch(PDOException $e){
        echo $e->getMessage();
    }
    
        2
  •  0
  •   Community Mohan Dere    9 年前

    尝试 $stm->rowCount() 。此处来源: http://php.net/manual/en/pdostatement.rowcount.php

    这里也已经提出了这个问题: https://stackoverflow.com/a/10522575/2853903