Check if a table exists in MySQL from PHP


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;
}

, , , , , ,

  1. #1 by słomki do napojów on December 1, 2013 - 4:04 am

    You actually make it seem so easy with your presentation but I find this matter to
    be actually something which I think I would never understand.
    It seems too complicated and very broad for me. I’m looking forward
    for your next post, I’ll try to get the hang of it!

(will not be published)