get number of rows with pdo

后端 未结 5 1383
自闭症患者
自闭症患者 2020-12-16 00:29

I have a simple pdo prepared query:

$result = $db->prepare(\"select id, course from coursescompleted where person=:p\"); 
$result ->bindParam(\':p\', $         


        
相关标签:
5条回答
  • 2020-12-16 01:18

    You can use this

    <?php
    $result = $db->prepare("select id, course from coursescompleted where person=:p"); 
    $result ->bindParam(':p', $q, PDO::PARAM_INT);
    $result->execute();
    $rows = $result->rowCount();
    echo $rows;
    ?>
    

    This sometimes does not work on SELECT queries. But based on personal experience, and since you didn't mention porting it to other database systems, it should work on MySQL.

    More info is in PHP manual here

    0 讨论(0)
  • 2020-12-16 01:20

    You've executed a query that returns rows from the database, fetched the first row from the result into a variable and then echo'd the first column of that row.

    If you want to count, do an SQL count()

    $result = $db->prepare("select count(*) from coursescompleted where person=:p"); 
    $result->bindParam(':p', $q, PDO::PARAM_INT);
    $result->execute();
    $rowCount = $result->fetchColumn(0);
    echo $rowCount;
    
    0 讨论(0)
  • 2020-12-16 01:20

    Assuming id is the primary key use:

     SELECT COUNT(id) FROM coursescompleted WHERE person=:p;
    

    Avoid a count(*). If your storage engine is InnoDB (possibly others except MyIsam) you'll take a performance hit.

    0 讨论(0)
  • 2020-12-16 01:21

    Try echo count($rows); as $rows is an array.

    Edit:

    To use the results

    $rows = $result->fetchAll(/* nothing here */);
    if(count($rows) > 0) {
      // Show results, perhaps using a foreach($rows as $row)
    } else {
     echo "Sorry, no results found";
    }
    
    0 讨论(0)
  • 2020-12-16 01:30

    PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

    You aren't fetching the row-count at all.

    SELECT COUNT(*) FROM coursescompleted where person=:p
    

    This query would return total rows in $rows[0];

    EDIT: Please see @ray's answer. using count(id) is better than count(*) for InnoDB.


    You could get row-count in the following manner, from your earlier query.

    $row_count = $result->rowCount();
    

    But be warned:

    If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

    Documentation

    0 讨论(0)
提交回复
热议问题