开发者

PHP/PDO more efficient method of rows?

I have all my sites built on php and mysql stack using PDO. I am well aware of the various ways to find out how many rows a specific query can return but I am not sure how to find out 开发者_开发百科which is more efficient.

Method 1 - COUNT() in SQL

$stmt = $db->prepare('SELECT COUNT(ID) FROM table WHERE name = :name');
$stmt->bindParam(':name', $name);
$stmt->execute();

while($row = $stmt->fetch()) {
    $counter = $row[0];
}

in this example, I am ONLY interested in counting the number of results for a specific query. The query is made once and results are returned in a $counter variable.

Method 2 - Foundrows

$stmt = $db->prepare('SELECT ID FROM table WHERE name = :name');
$stmt->bindParam(':name', $name);
$stmt->execute();

$counter= $db->query("SELECT FOUND_ROWS()")->fetchColumn();

This method issues a follow up call to my initial query.

Method one seems to be the most 'efficient' in terms of only making one query to the database and finding the result. Method 2 gives the added benefit of allowing me to retrieve a set of results, then based on the count of those results choose to disregard or continue. Method 2, however, appears to make subsequent calls which i would assume is less efficient.

Any seasoned advice on this?

note: in this example, I am ONLY interested in what is more efficient to find the number of result rows. Additional FYI info about added benefits of each is appreciated but not the point of the question.


Method 1 is more efficient.
If id is not the primary key, then replace count(id) with count(*) for extra speed (maybe faster, never slower).
If you don't have an index on name add one for speed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜