How can I count the numbers of rows that a MySQL query returned?

后端 未结 11 1926
北海茫月
北海茫月 2020-11-28 04:51

How can I count the number of rows that a MySQL query returned?

11条回答
  •  庸人自扰
    2020-11-28 05:25

    As it is 2015, and deprecation of mysql_* functionality, this is a PDO-only visualization.

    ';
        try {
            $theCategory="fruit";   // value from user, hard-coded here to get one in
    
            $dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
            // prepared statement with named placeholders
            $stmt = $dbh->prepare("select id,foodName from foods where category=:theCat and perishable=1");
            $stmt->bindParam(':theCat', $theCategory, PDO::PARAM_STR,20);
            $stmt->execute();
            echo "rowCount() returns: ".$stmt->rowCount().$b;   // See comments below from the Manual, varies from driver to driver
    
            $stmt = $dbh->prepare("select count(*) as theCount from foods where category=:theCat and perishable=1");
            $stmt->bindParam(':theCat', $theCategory, PDO::PARAM_STR,20);
            $stmt->execute();
            $row=$stmt->fetch();    // fetches just one row, which is all we expect
            echo "count(*) returns: ".$row['theCount'].$b;
    
            $stmt = null;
            // PDO closes connection at end of script
        } catch (PDOException $e) {
            echo 'PDO Exception: ' . $e->getMessage();
            exit();
        }
    ?>
    

    Schema for testing

    create table foods
    (   id int auto_increment primary key,
        foodName varchar(100) not null,
        category varchar(20) not null,
        perishable int not null
    );
    insert foods (foodName,category,perishable) values 
    ('kiwi','fruit',1),('ground hamburger','meat',1),
    ('canned pears','fruit',0),('concord grapes','fruit',1);
    

    For my implementation, I get the output of 2 for both echos above. The purpose of the above 2 strategies is to determine if your driver implementation emits the rowCount, and if not, to seek a fall-back strategy.

    From the Manual on PDOStatement::rowCount:

    PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.

    For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

提交回复
热议问题