Use php to check if a table exists
Posted: Thu May 11, 2006 1:07 pm
I'm creating a php install file to setup a database.
How do I check to see if the table already exists?
How do I check to see if the table already exists?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
//Verifies that a MySQL table exists
$adstable = "{$ezine_id}_adverts";
function fnTableExists($adstable) {
include "path/to/connection/script";
if (!$oConn = mysql_connect($host,$uname,$pword)) {
$bRetVal = FALSE;
} else {
$bRetVal = FALSE;
$result = mysql_list_tables('database_name', $oConn);
while ($row=mysql_fetch_array($result, MYSQL_NUM)) {
if ($row[0] == $adstable)
$bRetVal = TRUE;
// Code here for SQL query - insert a row into the edverts table for this ezine
break;
}
mysql_free_result($result);
//mysql_close($oConn);
}
return ($bRetVal);
echo $bRetVal;
}
fnTableExists("{$ezine_id}_adverts"); // Calls the functionCode: Select all
CREATE TABLE [IF NOT EXISTS] `arcade_categories` (
`catid` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
`catname` VARCHAR( 250 ) NOT NULL ,
`displayorder` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL ,
PRIMARY KEY ( `catid` ) ,
UNIQUE (
`catname` ,
`displayorder`
)
) TYPE = MYISAM ;Code: Select all
$sql = "CREATE TABLE IF NOT EXISTS `arcade_categories` (
`catid` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
`catname` VARCHAR( 250 ) NOT NULL ,
`displayorder` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL ,
PRIMARY KEY ( `catid` ) ,
UNIQUE (
`catname` ,
`displayorder`
)
) TYPE = MYISAM ;";
$result=mysql_query($sql) or die(mysql_error());Only one way to find out....Citizen wrote:Ok, final copy (if no errors):
Is that going to work?Code: Select all
$sql = "CREATE TABLE IF NOT EXISTS `arcade_categories` ( `catid` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT , `catname` VARCHAR( 250 ) NOT NULL , `displayorder` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL , PRIMARY KEY ( `catid` ) , UNIQUE ( `catname` , `displayorder` ) ) TYPE = MYISAM ;"; $result=mysql_query($sql) or die(mysql_error());
HUH? The whole point of the query to to only create a new table if the table Doesn't exist. You can always do DROP IF EXISTS too...Citizen wrote:I ran into only one problem... if i refresh the install file and run it again, it doesnt return an error if the table exists. What did I do wrong?