Php SQL ScriptAt times we want to find if a tables exists in a database.The snippet below shows how this can be done.

It open a db connection or reuse an already db connection, then selects the given database and finally executes a sql to find out whether the table exists or not. <!>

 

 

<?

/**
* This function checks if a table exists in a
* given database and returns a boolean
*/


function table_exists($table, $database, $link) {

// select the database
mysql_select_db($database, $link);

// query
$exists = mysql_query("SELECT 1 FROM `$table` LIMIT 0", $link);

// check it exists
if ($exists)
return true;
else
return false;
}

/**
* Example on how to use
*/


$table = "host";
$database = "mysql";

// connnect to the database server
$link = mysql_connect("localhost", "root", "",false);

if (!$link) {
die('Could not connect to database: ' . mysql_error());
}

// invoke the function
if (table_exists($table, $database,$link)) {
printf("Table found");
} else {
printf("Table does not exists");
}

// finally close the connection
mysql_close($link);
?>