如何在sql create语句中使用变量名作为表名

时间:2022-01-10 22:23:40

I need to create a new table in sql database based on input given by user.I want something like this

我需要根据user提供的输入在sql数据库中创建一个新表。我想要这样的东西

$query = "CREATE TABLE . $POST['name'] . (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);";

The user enters name in input text box and submits.Then the above query is called.Is it possible to create table dynamically with variable name.I am trying to do it in mysql. I am new to sql.

用户在输入文本框中输入名称并提交。然后调用上述查询。是否可以使用变量名称动态创建表。我正在尝试在mysql中执行此操作。我是sql的新手。

Thanks in Advance

提前致谢

3 个解决方案

#1


2  

You could surround the variable with curly brackets, like this:

您可以用大括号括起变量,如下所示:

$query = "CREATE TABLE {$_POST['name']} (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)";

#2


1  

Answering my own question so that it could be useful for others...

回答我自己的问题,以便它对其他人有用......

Storing the POST variable previously in a local variable and giving the local variable in sql statment worked fine for me.

将POST变量先前存储在局部变量中并在sql语句中给出局部变量对我来说很好。

$table_name = $_POST['name'];

$query = "CREATE TABLE $table_name (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)";

#3


0  

$query = "CREATE TABLE $_POST['name'] (
   PersonID int,
   LastName varchar(255),
   FirstName varchar(255),
   Address varchar(255),
   City varchar(255)
)";

your syntax is incorrect. that's all

你的语法不正确。就这样

#1


2  

You could surround the variable with curly brackets, like this:

您可以用大括号括起变量,如下所示:

$query = "CREATE TABLE {$_POST['name']} (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)";

#2


1  

Answering my own question so that it could be useful for others...

回答我自己的问题,以便它对其他人有用......

Storing the POST variable previously in a local variable and giving the local variable in sql statment worked fine for me.

将POST变量先前存储在局部变量中并在sql语句中给出局部变量对我来说很好。

$table_name = $_POST['name'];

$query = "CREATE TABLE $table_name (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)";

#3


0  

$query = "CREATE TABLE $_POST['name'] (
   PersonID int,
   LastName varchar(255),
   FirstName varchar(255),
   Address varchar(255),
   City varchar(255)
)";

your syntax is incorrect. that's all

你的语法不正确。就这样