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

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

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

相关标签:
11条回答
  • 2020-11-28 05:23

    In the event you have to solve the problem with simple SQL you might use an inline view.

    select count(*) from (select * from foo) as x;
    
    0 讨论(0)
  • 2020-11-28 05:24

    If you're fetching data using Wordpress, then you can access the number of rows returned using $wpdb->num_rows:

    $wpdb->get_results( $wpdb->prepare('select * from mytable where foo = %s', $searchstring));
    echo $wpdb->num_rows;
    

    If you want a specific count based on a mysql count query then you do this:

    $numrows = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM mytable where foo = %s', $searchstring );
    echo $numrows;
    

    If you're running updates or deletes then the count of rows affected is returned directly from the function call:

    $numrowsaffected = $wpdb->query($wpdb->prepare(
       'update mytable set val=%s where myid = %d', $valuetoupdate, $myid));
    

    This applies also to $wpdb->update and $wpdb->delete.

    0 讨论(0)
  • 2020-11-28 05:25

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

    <?php
        // Begin Vault (this is in a vault, not actually hard-coded)
        $host="hostname";
        $username="GuySmiley";
        $password="thePassword";
        $dbname="dbname";
        // End Vault
    
        $b='</br>';
        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.

    0 讨论(0)
  • 2020-11-28 05:28
    SELECT SQL_CALC_FOUND_ROWS *
    FROM   table1
    WHERE  ...;
    
    SELECT FOUND_ROWS();
    

    FOUND_ROWS() must be called immediately after the query.

    0 讨论(0)
  • 2020-11-28 05:30

    The basics

    To get the number of matching rows in SQL you would usually use COUNT(*). For example:

    SELECT COUNT(*) FROM some_table
    

    To get that in value in PHP you need to fetch the value from the first column in the first row of the returned result. An example using PDO and mysqli is demonstrated below.

    However, if you want to fetch the results and then still know how many records you fetched using PHP, you could use count() or avail of the pre-populated count in the result object if your DB API offers it e.g. mysqli's num_rows.

    Using MySQLi

    Using mysqli you can fetch the first row using fetch_row() and then access the 0 column, which should contain the value of COUNT(*).

    // your connection code
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new \mysqli('localhost', 'dbuser', 'yourdbpassword', 'db_name');
    $mysqli->set_charset('utf8mb4');
    
    // your SQL statement
    $stmt = $mysqli->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
    $stmt->bind_param('s', $someVariable);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // now fetch 1st column of the 1st row 
    $count = $result->fetch_row()[0];
    
    echo $count;
    

    If you want to fetch all the rows, but still know the number of rows then you can use num_rows or count().

    // your SQL statement
    $stmt = $mysqli->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
    $stmt->bind_param('s', $someVariable);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // If you want to use the results, but still know how many records were fetched
    $rows = $result->fetch_all(MYSQLI_ASSOC);
    
    echo $result->num_rows;
    // or
    echo count($rows);
    

    Using PDO

    Using PDO is much simpler. You can directly call fetchColumn() on the statement to get a single column value.

    // your connection code
    $pdo = new \PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '', [
        \PDO::ATTR_EMULATE_PREPARES => false,
        \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
    ]);
    
    // your SQL statement
    $stmt = $pdo->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
    $stmt->execute([
        $someVariable
    ]);
    
    // Fetch the first column of the first row
    $count = $stmt->fetchColumn();
    
    echo $count;
    

    Again, if you need to fetch all the rows anyway, then you can get it using count() function.

    // your SQL statement
    $stmt = $pdo->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
    $stmt->execute([
        $someVariable
    ]);
    
    // If you want to use the results, but still know how many records were fetched
    $rows = $stmt->fetchAll();
    
    echo count($rows);
    

    PDO's statement doesn't offer pre-computed property with the number of rows fetched, but it has a method called rowCount(). This method can tell you the number of rows returned in the result, but it cannot be relied upon and it is generally not recommended to use.

    0 讨论(0)
  • 2020-11-28 05:34
    > SELECT COUNT(*) AS total FROM foo WHERE bar= 'value';
    
    0 讨论(0)
提交回复
热议问题