BluGeni
BluGeni

Reputation: 3454

Cannot create MySQL table with "if not exists"

Here is my code:

$STH1000=$DBH->query("CREATE TABLE IF NOT EXISTS '".$dept.$year."' ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ") or die "Could not prepare sql statement";

All I'm trying to do is create a table if $dept$year doesn't exist but the way I have it now, it throws errors.

I believe there is a way to create a table is mysql returns an error on a select but I'm not sure how to do that either. Any help would be greatly appreciated.

Upvotes: 1

Views: 1029

Answers (2)

Arif
Arif

Reputation: 1211

just remove quotes from '".$dept.$year."' as ".$dept.$year."

your query will be like this

$STH1000=$DBH->query("CREATE TABLE IF NOT EXISTS ".$dept.$year." ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ") or die "Could not prepare sql statement";

Upvotes: 1

Valera Leontyev
Valera Leontyev

Reputation: 1181

$STH1000=$DBH->query("CREATE TABLE IF NOT EXISTS ".$dept.$year." ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ") or die "Could not prepare sql statement";

Table name must not be closed in '' (but my be optionally closed in ``).

Upvotes: 4

Related Questions