As simple in theory as it sounds I\'ve done a fair amount of research and am having trouble figuring this out.
How can I check if a MySQL table exists and if it does
mysql_unbuffered_query("SET profiling = 1"); // for profiling only
@mysql_unbuffered_query("SELECT 1 FROM `table` LIMIT 1 ");
if (mysql_errno() == 1146){
// NO EXISTING TABLE CODE GOES HERE
}
elseif(mysql_errno() > 0){
echo mysql_error();
}
$results = mysql_query("SHOW PROFILE"); // for profiling only
Execution time, measured using mysql profiling, when a table exists, or not, is about .000125 sec. (125µs)
The LIMIT 1 is important for speed. This minimizes the Sorting Result and Sending Data query State times. And table size is not a factor.
I always use an unbuffered query when no results are required.
PROFILE RESULTS WHEN TABLE DOES NOT EXIST
QUERY STATE SECONDS
-------------------- -------
starting 0.000025
checking permissions 0.000006
Opening tables 0.000065
query end 0.000005
closing tables 0.000003
freeing items 0.000013
logging slow query 0.000003
cleaning up 0.000003
TOTAL 0.000123 <<<<<<<<<<<< 123 microseconds
WHEN TABLE EXISTS
QUERY STATE SECONDS
-------------------- -------
starting 0.000024
checking permissions 0.000005
Opening tables 0.000013
System lock 0.000007
init 0.000006
optimizing 0.000003
statistics 0.000009
preparing 0.000008
executing 0.000003
Sending data 0.000019
end 0.000004
query end 0.000004
closing tables 0.000006
freeing items 0.00001
logging slow query 0.000003
cleaning up 0.000003
TOTAL 0.000127 <<<<<<<<<<<< 127 microseconds