Skip to content
July 8, 2008 / ranacse05

Get the Row Number in PDO

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 = preg_replace(‘~ORDER\s+BY.*?$~sD’, ”, $sql);
$stmt = $dbh->query($sql);
$r = $stmt->fetchColumn(0);
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 .



Leave a Comment
  1. hasin / Jul 8 2008 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?

  2. ranacse05 / Jul 8 2008 7:50 pm

    @Hasin Bhai
    thanks for ur advice . Its so easy . 😀

  3. anonymous / Aug 20 2008 9:37 am

    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:

    Which should be correct. Am I missing something? Yes, I am using PDO

  4. ranacse05 / Aug 23 2008 7:18 am

    I wasn’t working with me . And as the says that its only work when the query change the database .

  5. Erik / Nov 30 2008 8:47 pm

    It works for some DBs.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: