Two quick (I hope!) questions:
Counting rows
Is it more efficient to use COUNT(id) in an SQL query, or to just select all the rows and use PHP’s mysql_num_rows() function on the returned resource? Would this depend on the size of the results query? Is there a fairly easy way of determining the answer to this question?
Results arrays
At the moment, I am using COUNT(id) in a query, and then obviously using mysql_query() and mysql_fetch_array(), as follows:
$sql = "SELECT COUNT(id) FROM TABLE1;";
$resource = mysql_query($sql) or die(mysql_error())
$result = mysql_fetch_array($resource);
$count = $result[0];
and this returns the number of rows fine. However, I’m surprised that
$count = mysql_fetch_array($resource)[0];
doesn’t work; I get the error:
Parse error: syntax error, unexpected '[' in C:\ServerDocs\file1.php on line 44
is there an easy explanation as to what’s going on?
Thanks in advance,
Chris
It depends on the situation, but
SELECT COUNT(*)is normally faster.The reason is simply that using
mysql_num_rows(), the databaseserver has to actually build the result set. With a
COUNT(*), on theother hand, the DB may be able to determine the number of rows just
from indexes, which is much faster. So if all you want is the count,
then
mysql_num_rows()ends up doing a lot more work for the sameresult.
Another down side is that mysql_num_rows doesn’t work with
unbuffered queries. So if you need to work with very large result
sets, using mysql_num_rows might not be an option. However,
COUNT(*)is always available.
$count = mysql_fetch_array($resource)[0];This type of statements are not possible in current version of php.
So, better use