In PHP, resources are returned from certain functions so that they can be passed to other related functions. Examples include database connections, database query results, file-handles, etc.
According to the documentation on mysql_query()
, a SELECT query returns a resource. You can take that resource and pass it to a number of different functions. To retrieve a count of the rows, you can use mysql_num_rows()
, to retrieve the results of the query, you can use either mysql_fetch_array()
, mysql_fetch_assoc()
or mysql_fetch_object()
.
A normal pattern for dealing with database results will look something like this:
$result = mysql_query("SELECT * FROM persons"); // run query against database
$count = mysql_num_rows($result); // retrieve a count of the rows in the previous query
while ($row = mysql_fetch_assoc($result)) { // loop through all the rows in the resultset
// use $row['column_name'] to access columns in your resultset
}
From your example above:
$result = mysql_query("SELECT COUNT(*) AS num FROM persons"); // run query against db
$row = mysql_fetch_assoc($result); // retrieve the 1 (and only) row
$count = $row['num']; // we needed to alias the COUNT(*) column as `num`