Using SELECT COUNT MYSQL statement with PHP

If you want to return the results of a count operation in MYSQL, this example may help:

I used PHP Version 5.2.0 and MYSQL version 5.0.22 for this example.

SELECT COUNT(field name)

What this query does is basically counts all the rows in the user_logged_in table and returns the result in the "tempCnt" variable.


This example assumes you have an "id" field in your "users_logged_in" table.

Using SELECT COUNT()

$query = "SELECT count(id) AS tempCnt
FROM users_logged_in";

$goPage = mysql_query($query);

if(!$goPage)
die("ERROR_PAGE_SQL");

$usersViewingPage = mysql_result($goPage,0,`tempCnt`);


If you are curious about when you would use something like SELECT COUNT() opposed to mysql_num_rows():
Keep in mind that SELECT COUNT() is useful only if you need the number of rows returned. If you also need the data from the rows, then the more ideal method would be:

Using SELECT *

$query = "SELECT *
FROM users_logged_in";

$goPage = mysql_query($query);

if(!$goPage)
die("ERROR_PAGE_SQL");

$usersViewingPage = mysql_num_rows($goPage);

//You could use mysql_result() or mysql_fetch_rows(), etc... to get the data.

Keywords: php mysql SELECT COUNT


Submit a Comment