views:

81

answers:

4

I'm currently using the following which works but throws an error every time the table is created (as it is first trying to insert into a db which does not exist and returning false).

$result = $dbh->prepare("INSERT INTO `". $host ."` (URL) VALUES ('$href')");
if( ! $result->execute() ){
    $result = $dbh->prepare("CREATE TABLE `" . $host . "` ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ENGINE = MYISAM ;");
    $result->execute();
    print "Host added: " . $host . "\n";
}

Could someone let me know of a more efficient way of completing this task?

Regards,

Phil

EDIT - Bind

$result = $dbh->prepare("CREATE TABLE `?` If NOT EXISTS ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ENGINE = MYISAM ;");
            $result->execute($host);
            $result = $dbh->prepare("INSERT INTO `?` (URL) VALUES ('?')");
            $result->execute($host, $href);
            print "Host added: " . $host . "\n";

is this correct?

+4  A: 
CREATE TABLE Foo if NOT EXISTS  <schema>

Also, please use placeholders and bind values in your INSERT operations, lest you be known as Little Bobby Tables.

Ether
About this 'bind' thing, can you check the edit in the question to see if it correct?
Phil Jackson
@Phil: your code looks good to me.
Ether
Actually you can't use placeholders for table names (for most drivers), so the edited code will fail.
CanSpice
@CanSpice: it definitely varies. MySQL will allow prepared statements for identifiers in *some* circumstances, but usually only if you sacrifice a chicken and mutter the right incantation first - e.g. see the evil tricks in http://dev.mysql.com/doc/refman/5.1/en/user-variables.html.
Ether
@Phil: an alternative to placeholders for your table names would be to use the `quote_identifier` function in DBI -- `$dbh->prepare("CREATE TABLE " . $dbh->quote_identifier($host) . " IF NOT EXISTS ...")`
Ether
http://bobby-tables.com
daxim
A: 

Try:

CREATE TABLE tblname IF NOT EXISTS ...
mluebke
A: 

Is this a web app? If so, I highly recommend against using a user/pass that has rights to alter the database structure. A more typical method would be to have an installer script that creates the tables up front.

GrandmasterB
not if you dont know what they are going to be called
Phil Jackson
Why not implment it in a single table, with Host being a column name that you can filter on?
GrandmasterB
@Phil if you don't know what they're going to be called, your database design is broken :)
hobbs
A: 

If you expect the table to exist more often than not, the existing code is the most efficient way. Note that you can override PrintError and RaiseError (assuming one of those is what you mean by "throws an error") for a given statement handle.

ysth