Sometimes its necessary to execute a query or execute some code if a table exists or not. So a bit of searching got me to the conclusion that mysql doesn’t have a direct query or method for it from php. So there are two methods to do it.
- Use the mysql command show tables . Which will give me the list of tables and then parse and check if the table I want is present or not
- Use the php function to get the list of tables and check if the table needed is present in that list.
I felt the second method is better suited and so I will explain that method only.
So the method is simple. Just get the list of tables in a database by using the function mysql_list_tables and iterate thought the list to check if the table exists or not and return true or false accordingly. So here is the code.
function tableExists($tablename) {
// Get a list of tables contained within the database.
$result = mysql_list_tables("DBNAME");
$rcount = mysql_num_rows($result);
// Check each in list for a match.
for ($i=0;$i<$rcount;$i++) {
if (mysql_tablename($result, $i)==$tablename) return true;
}
return false;
}
Recent Comments