Actually, the initially posted SELECT COUNT(*) approach is flawless. SELECT COUNT(*) will provide one and only one row in response unless you can't select from the table at all. Even a brand new (empty) table responds with one row to tell you there are 0 records.
While other approaches here are certainly functional, the major problem comes up when you want to do something like check a database to ensure that all the tables you need exist, as I needed to do earlier today. I wrote a function called tables_needed() that would take an array of table names -- $check -- and return either an array of tables that did not exist, or FALSE if they were all there. With mysql_list_tables(), I came up with this in the central block of code (after validating parameters, opening a connection, selecting a database, and doing what most people would call far too much error checking):
if($result=mysql_list_tables($dbase,$conn))
{ // $count is the number of tables in the database
$count=mysql_num_rows($result);
for($x=0;$x<$count;$x++)
{
$tables[$x]=mysql_tablename($result,$x);
}
mysql_free_result($result);
// LOTS more comparisons here
$exist=array_intersect($tables,$check);
$notexist=array_diff($exist,$check);
if(count($notexist)==0)
{
$notexist=FALSE;
}
}
The problem with this approach is that performance degrades with the number of tables in the database. Using the "SELECT COUNT(*)" approach, performance only degrades with the number of tables you *care* about:
// $count is the number of tables you *need*
$count=count($check);
for($x=0;$x<$count;$x++)
{
if(mysql_query("SELECT COUNT(*) FROM ".$check[$x],$conn)==FALSE)
{
$notexist[count($notexist)]=$check[$x];
}
}
if(count($notexist)==0)
{
$notexist=FALSE;
}
While the increase in speed here means virtually nothing to the average user who has a database-driven backend on his personal web site to handle a guestbook and forum that might get a couple hundred hits a week, it means EVERYTHING to the professional who has to handle tens of millions of hits a day... where a single extra millisecond on the query turns into more than a full day of processing time. Developing good habits when they don't matter keeps you from having bad habits when they *do* matter.