Checking for existence of MySQL table

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Checking for existence of MySQL table

Post by mjseaden »

Hi,

Can you tell me if any PHP functions or MySQL codes allow to check for the existence of a given table. I've looked up my SQL reference and can't seem to see any function that facilitates this.

Many thanks

Mark
User avatar
phpScott
DevNet Resident
Posts: 1206
Joined: Wed Oct 09, 2002 6:51 pm
Location: Keele, U.K.

Post by phpScott »

not sure how to use the results but there are two ways I can think off.
1)do a simple select and check the error code for the message 'table tablename doesn't exists' type thing or check for error number 1146 I think.
or
2) use 'SHOW TABLES' and loop through the results to see if the table your looking for exists.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

don't know if this is what I think it is or not, but there's "IF NOT EXISTS"
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

re

Post by harrisonad »

why not query the table then check if an error occur:

Code: Select all

$tablename = "sometable";
query = "select * from $tablename";
if(mysql_query($query))
   echo "table exists";
else
   echo "table doesn't exists";
just make sure your query is correct.
User avatar
Calimero
Forum Contributor
Posts: 310
Joined: Thu Jan 22, 2004 6:54 pm
Location: Milky Way

...

Post by Calimero »

Found this on php.net - mysql_list_tables() :

http://www.php.net/manual/en/function.m ... tables.php

or maybe mysql_table_name() - check the php.net for exact function name.

My proposition:

List tables, check if yours exist, do whatever with result.


Or do a mysql_query for checking the existence of a table ( in good old sql code - which I don't know how to do it :D )
Post Reply