General Question

richardhenry's avatar

How do I check for the existence of a particular MySQL table using PHP? (Using an IF statement.)

Asked by richardhenry (12692points) June 18th, 2008

I need to check whether or not the table ‘content’ exists in a particular database using PHP. If the table doesn’t exist, I need to handle the situation differently.

I basically need an IF statement to check for the existence of this table. How should I do this? I’m looking at ‘show tables’, but can’t really see how I would deal with the data in the application. Any help would be appreciated.

Observing members: 0 Composing members: 0

4 Answers

lefteh's avatar

I don’t know of a preexisting function, so here’s one I wrote real quick (untested):

function checkTable ($table_name, $database_name) {
$my_tables = mysql_list_tables($database_name);
while (list($foo) = mysql_fetch_array($my_tables)) {
if ($foo == $table_name) return true;
}
return false;
}

if (checkTable(“content”, “your_database”)) {

// Table exists

} else {

// Table does not exist

}

paulc's avatar

There’s no facility in SQL (MySQL’s implementation anyway) to check for the existence of a table so lefteh’s method should do the trick.

richardhenry's avatar

Thanks! Reworked it into a switch and I’m ready to go.

chaosrob's avatar

From the phpMyAdmin sources:

/**
* Ensures the database exists (else move to the “parent” script) and displays
* headers
*/
if (!isset($is_db) || !$is_db) {
// Not a valid db name -> back to the welcome page
if (strlen($db)) {
$is_db = PMA_DBI_select_db($db);
}
if (! strlen($db) || !$is_db) {
PMA_sendHeaderLocation($cfg[‘PmaAbsoluteUri’] . ‘main.php?’ . PMA_generate_common_url(’’, ’’, ’&’) . (isset($message) ? ’&message=’ . urlencode($message) : ’’) . ’&reload=1’);
exit;
}
} // end if (ensures db exists)

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther