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?
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With