Use php to check if a table exists
Moderator: General Moderators
Use php to check if a table exists
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?
- jayshields
- DevNet Resident
- Posts: 1912
- Joined: Mon Aug 22, 2005 12:11 pm
- Location: Leeds/Manchester, England
There's probably a proper way to do this, but if you want a quick workaround why not run count the records in the table name you want to check for existance, if it returns > 1 then it's there. if it returns anything else drop the table (but don't die/exit on failure) and then (re) create it.
OK now I feel stupid, look up ^^^
OK now I feel stupid, look up ^^^
- mattcooper
- Forum Contributor
- Posts: 210
- Joined: Thu Mar 17, 2005 5:51 am
- Location: London, UK
Here's one I developed today to do just that:
That will do the trick for you!
Hope this helps...
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 functionHope this helps...
So my code should look like this?
Code: 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 ;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());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());
EDIT: BTW/ worked for me