Faqts : Computers : Programming : Shopping For You : PHP : Database Backed Sites : General

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

451 of 537 people (84%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How do I get out the result of a query like "select count(*) from $table"?

Nov 12th, 2008 02:25
Hindusthan Jobs, Richard Lynch, Nathan Wallace,


All you need to do is:

    $result=mysql_db_query($database,"select count(*) from $table");
    $count=mysql_result($result,0,"count(*)");

Alternatively, you can use the numerical field offset.  For example:

    $result=mysql_db_query($database,"select count(*) from $table");
    $count = mysql_result($result,0,0);

You should be careful to check that the database returns a valid result
however, so the following code is a better example:

    $result = mysql_db_query($database,"select count(*) from $table");
    $count = ($result>0) ? mysql_result($result,0,0) : 0;

Using the numerical offset is much faster than specifying the column
name.  But, sometimes a column name makes coding much easier.  In these
cases you can just name the count(*) result in the database query.  The
code below gives count(*) the name "bar":

[I am not 100% sure, but I don't think using mysql_result($result,0,0)
is any faster than mysql_result($result,0,"count(*)")... The reader is
encouraged to test and confirm.]

    $result=mysql_db_query($database,
                           "select count(*) as bar from $table");
    $count = mysql_result($result,0,"bar");

    http://www.php.net/manual/function.mysql-result.php3

An alternative to using mysql_result is to get the whole row at once as
an array with:

    list($count)=mysql_fetch_row($result);

Don't be tempted to use mysql_num_rows(), using count(*) is a lot
faster.  If you use "select * from table" and then mysql_num_rows() you
ask the SQL server to return ALL entries (could be millions).  Count(*)
just returns the number of elements.
http://www.hindusthanjobs.com