0

I'm trying to count the number of rows returned by a query, and I'm doing like this:

$what = 'Norman';
$stmt = $conn->prepare('select names as names from names where names = :what');
$stmt->bindParam('what', $what);
$stmt->execute();
$rows = $stmt->fetchColumn();

echo 'Rows found '.$rows;

$stmt->setFetchMode(PDO::FETCH_ASSOC);

while($row = $stmt->fetch())
{  
    echo $row['names'] . "<br>";
}

But I keep getting nothing at all. Just blank. Whats the right way to do this?

Norman
  • 6,159
  • 23
  • 88
  • 141

2 Answers2

7

Looks like you are using improper functions here.

$what = 'Norman';
$stmt = $conn->prepare('select names from names where names = ?');
$stmt->execute(array($what));
$rows = $stmt->fetchAll(); // it will actually return all the rows

echo 'Rows found '.count($rows);

foreach ($rows as $row)
{  
    echo $row['names'] . "<br>";
}

or you can make it even neater, by getting 1d array instead of 2d

$rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); 

echo 'Rows found '.count($rows);

foreach ($rows as $name)
{  
    echo $name . "<br>";
}

But you have to check for PDO errors first

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
2

If you want to get the number of rows returned use rowCount

// ...
$rows = $stmt->rowCount();

echo 'Rows found '.$rows;
// ...
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • I thought this does not work with mysql, but it's actually returning the number of rows in the table. I've read all over that rowCount() does not work with selects {Amazed}. – Norman Apr 26 '13 at 09:48
  • @Norman It does not work on some database systems. It does not list the working ones. – Sirko Apr 26 '13 at 10:12