get number of rows with pdo

眉间皱痕 提交于 2019-12-29 06:15:41

问题


I have a simple pdo prepared query:

$result = $db->prepare("select id, course from coursescompleted where person=:p"); 
$result ->bindParam(':p', $q, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];

the echo seems to be returning the ID value of the record, not the number of records returned by the query?

any idea or explanation for this?


回答1:


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




回答2:


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;



回答3:


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.




回答4:


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";
}



回答5:


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



来源:https://stackoverflow.com/questions/13195920/get-number-of-rows-with-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!