samyb8
samyb8

Reputation: 2588

Count rows of a table using PDO

I was wondering, what is the best way to count the rows of a table with PHP using PDO?

Here is what I have, but not getting anything for $count.

$count = $con -> query("SELECT COUNT(*) FROM item_descr")->fetch(PDO::FETCH_NUM);
echo $count[0];
if (count($count)>0)
{
$subStatus = "The email introduced is already in our database.";
}

Upvotes: 0

Views: 1077

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562240

There's no reason to use the PHP count() function on the array returned by fetch(). The count has already been calculated in SQL, so you want the value stored in the result, not the count of results.

Here's how I would write it:

$countStmt = $con->query("SELECT COUNT(*) FROM item_descr");
if ($countStmt === false) {
  // do something to report the error
}
$count = 0;
while ($row = $countStmt->fetch(PDO::FETCH_NUM)) {
  $count = $row[0];
}
if ($count > 0)
{
  $subStatus = "The email introduced is already in our database.";
}

Always check that the return value from query() is a valid PDOStatement. Any error causes it to return false, and the scalar value false is not an object with a fetch() method. In other words, you can't make the call in a fluent interface manner ($con->query()->fetch()), because query() is not guaranteed to return an object.

Upvotes: 2

Green Black
Green Black

Reputation: 5084

$count = $con->query("SELECT COUNT(*) as `num` FROM `item_descr`")
             ->fetch(PDO::FETCH_ASSOC);

echo $count['num'];

if ( $count['num'] > 0 )
{
  $subStatus = "The email introduced is already in our database.";
}

would work. If you do a COUNT in your query, you will ALWAYS have just ONE result, namely the number of rows. So count( $result) will always give you 1. In my example I use the COUNT from the query.

Upvotes: 1

Related Questions