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 descriptors, etc.
According to the documentation on mysql_query() the SELECT query returns a resource. You can take this resource and pass it to several different functions. To get the row count, you can use mysql_num_rows() to get the query results, you can use either mysql_fetch_array() , mysql_fetch_assoc() or mysql_fetch_object() .
A normal template for processing 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 the above example:
$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`
Dominic barnes
source share