Reputation: 5087
I am having trouble creating a SQL table with a PHP variable.
Let's say $tbl_date = "data";
mysql_query('CREATE TABLE '.$tbl_date.'
(
Test varchar(15),
Yes varchar(15),
Very int
)');
It doesn't create the table.
Upvotes: 0
Views: 5821
Reputation: 567
It looks like it's not working because your table name is not in the quotes. Try this:
mysql_query('CREATE TABLE `'.$tbl_date.'`
(
`Test` varchar(15),
`Yes` varchar(15),
`Very` int
)');
And the same applies for field names.
Also try this, it's easier to read by humans:
mysql_query("CREATE TABLE `{$tbl_date}`
(
`Test` varchar(15),
`Yes` varchar(15),
`Very` int
)");
Please note different types of quotes:
- single quotes and double quotes for building some string (eg.SQL query) in PHP
- back quotes used specially as a part of SQL query for table names and column names
Upvotes: 3
Reputation: 1032
Here is my work around:
$cars = "CREATE TABLE $tbl_date (
Test varchar(15),
Yes varchar(15),
Very int
)";
$results = mysql_query($cars) or die (mysql_error());
Upvotes: 1
Reputation: 980
I think you are missing the formatting ( single or double quotes etc) try this
$sql = "CREATE TABLE `user` (`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(255) NOT NULL, `address` TEXT NOT NULL) ENGINE = MyISAM;";
Upvotes: 1
Reputation: 3504
Yes you can.
mysql_query
takes a string so you can basically attach any dynamic string.
As suggested, you need to use backticks before and after the name of the table (and check if the user of your connection has the rights to create tables).
The main problem with this usage is that you are vulnerable to SQL injection (as long as you don't escape the $tbl_date
), so I suggest you to add far more controls to the variable used.
Also, adding dynamic tables to a database (excluding noSQL databases) is normally a BAD usage (check if you REALLY need this).
Upvotes: 0
Reputation: 1021
Yes but you must be careful that the user does't inject the code. Look into mySQL injection to ensure that your code is safe, otherwise a user could create or delete tables that you don't want them to have access to. Also, I don't see why you would want to, surely it would be better to create a table in the database and then add fields with rows that can be added afterwards.
Upvotes: 0