fwoelffel
fwoelffel

Reputation: 411

PHP MySQL CREATE TABLE

I'm trying to create a table using PHP, PDO and MySQL. For the needs of my application, the name of the table has to be a variable.

Here is my code :

$request = $pdo->prepare("CREATE TABLE IF NOT EXISTS :table (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `parent_id` bigint(20) unsigned NOT NULL,
      `position` bigint(20) unsigned NOT NULL,
      `left` bigint(20) unsigned NOT NULL,
      `right` bigint(20) unsigned NOT NULL,
      `level` bigint(20) unsigned NOT NULL,
      `title` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
      `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
      `content` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;");
$request->execute(array(
    'table'=>$uuid));

Can't I use ":table" in the MySQL statement ?? Currently I wrote :

[...]
CREATE TABLE IF NOT EXISTS `$uuid`
[...]

This works but it sounds weird to me ^^' Is it the only solution to my problem ?

Upvotes: 1

Views: 6000

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157828

$pdo->query("CREATE TABLE IF NOT EXISTS userfiles (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int unsigned NOT NULL,
  `parent_id` bigint(20) unsigned NOT NULL,
  `position` bigint(20) unsigned NOT NULL,
  `left` bigint(20) unsigned NOT NULL,
  `right` bigint(20) unsigned NOT NULL,
  `level` bigint(20) unsigned NOT NULL,
  `title` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  `content` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8");

This is THE ONLY proper way of handling such situations.
Such matters are very basic things.
and your current setup is just like a car with square wheels.
Despite of your shortage of time you have to make it single table.
Otherwise you will waste A LOT more time and eventually will turn to the proper design anyway but after innumerable pains

Upvotes: 2

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

You can't pass the table name as parameter. If you want to create table with variable name you must use dynamic query.

Upvotes: 4

Related Questions