zero-perfoliate
zero-perfoliate

Author Topic: Best method to count?  (Read 227 times)

Offline Oziam

  • PHP Workers
  • **
  • Posts: 23
  • Karma: +0/-0
Best method to count?
« on: October 04, 2010, 04:36:38 PM »
I want the quickest(least resource hungry) way of getting the number of specific rows from a large table. E.g I want to retrieve the number of entries by a specific username.

What would be the best method? To use COUNT or just SELECT num_rows?

Method 1:
-------------
$query = "SELECT COUNT(usrname) AS usrname FROM table WHERE usrname='$usrname' ";
$res = mysql_query($query) or die(mysql_error());
$array = mysql_fetch_array($res, MYSQL_ASSOC);
$count = $array['usrname'];

Method 2:
-------------
$query = "SELECT usrname FROM table WHERE usrname='$usrname' ";
$res = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($res);

Personally I think method 2 would be quicker but I read alot about using count() to speed things up.

Thanks!

Offline Oziam

  • PHP Workers
  • **
  • Posts: 23
  • Karma: +0/-0
Re: Best method to count?
« Reply #1 on: October 04, 2010, 08:21:40 PM »
No worries I found the answer!

Code: [Select]
$q1 = "SELECT COUNT(id) FROM table WHERE usrname='$usrname' ";
$r1 = mysql_query($q1) or die(mysql_error());
$count= mysql_result($r1,0);

mysql_free_result($r1); // only really needed if table has ALOT of entries //

Cheers....