To count SQL rows, is it more efficient to use PDO rowCount or count (*) AS?

In my script, I have about 15 SQL queries just to count the number of rows and display them to the user.

What is the most effective way?

Should I use:

$stmt=$cxn->prepare("SELECT id FROM items WHERE seller=?");
$stmt->execute(array($username));
echo $stmt->rowCount();

Or that:

$stmt=$cxn->prepare("SELECT count(*) as count FROM items WHERE seller=?");
$stmt->execute(array($username));   
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
    echo $row['count'];

Thanks in advance.

+3
source share
3 answers

Short answer: Count (*) will be faster.

However, this assumes that you are not using data if you are going to select data and want to count, then use your first method.

("SELECT id FROM items WHERE seller=?");

If you have an index in the table, then it will return almost instantly.

+2
source

The rowCount command can be used not only for SELECT queries, but also for UPDATE, INSERT, etc. So what's the use for this.

PDO:

.

, , , .

+1

It will be faster to use the number of rows in MySQL. Less bandwidth is needed between PHP and the database.

0
source

All Articles