Posted by: ranacse05 on: July 8, 2008
I was working on PHP Data Object (PDO) . But i saw that PDOstatement::rowCount() does not return row number for mysql when u use the SELECT command . Then i found this function to get the row number after a SELECT query .
<?
function getRowCount($sql)
{
$sql = trim($sql);
$sql = preg_replace(‘~^SELECT\s.*\sFROM~s’, ‘SELECT COUNT(*) FROM’,
$sql);
$sql = preg_replace(‘~ORDER\s+BY.*?$~sD’, ”, $sql);
$stmt = $dbh->query($sql);
$r = $stmt->fetchColumn(0);
$stmt->closeCursor();
return $r;
}
?>
Now call it like this
$sql = “SELECT name,email FROM user where userid=’$id’ “;
$totalBooks = getRowCount($sql);
This will return the effected row after the SELECT command .
Umm… I don’t get it. How come rowCount works for me but not for you?
Two tables; foo and faa. Foo table contains 4 rows, and faa 0. If I do query:
$fa = $db->query(“SELECT * FROM foo”);
$fo = $db->query(“SELECT * FROM faa”);
print $fa->rowCount().”".$fo->rowCount();
I get results:
4
0
Which should be correct. Am I missing something? Yes, I am using PDO
It works for some DBs.
July 8, 2008 at 7:46 pm
SELECT doesnt affect anything. only UPDATE and DELETE, INSERT DOES. so rowCount() wont return anything for select.
to get the number of rows returned, why dont u use just count() function treating it as array?