简体   繁体   English

使用变量创建SQL数据库表

[英]SQL database table creation with variable

I am working on a project, and I have to use sql. 我正在一个项目上,我必须使用sql。 The variable $file_name needs to be the table name, but when i try this: 变量$file_name需要是表名,但是当我尝试这样做时:

$sqlTableCreate = "CREATE TABLE ". $file_name . "( 
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
)";

The table does not create. 该表未创建。 I checked by using this: 我通过使用此检查:

if ($sqlConnection->query($sqlTableCreate) === TRUE) {  
    echo 'Created Sucessfully';
} else {
    echo 'Table does not create.';
}

I get 'Table does not create' when trying to use this. 尝试使用此方法时,显示'Table does not create' Help would be greatly appreciated. 帮助将不胜感激。 Thanks in advance! 提前致谢!

Your filename contains a extension, but I suspect you just want to use the name without the extension as the name of the table. 您的文件名包含扩展名,但是我怀疑您只想使用不带扩展名的名称作为表名。 You can use the basename function to remove the extension. 您可以使用basename函数删除扩展名。

$sqlTableCreate = "CREATE TABLE ". basename($file_name, ".csv") . "( 
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
)";

If there can be different extensions, and you want to remove them more generally, see 如果可以有其他扩展名,并且您想更一般地删除它们,请参见

How to remove extension from string (only real extension!) 如何从字符串中删除扩展名(仅实际扩展名!)

I don't see any issue with your posted query but couple things may be wrong 我看不到您发布的查询有任何问题,但几件事情可能是错误的

Make sure that there is no table exists with that same name. 确保不存在具有相同名称的表。 You can use IF NOT EXISTS marker to be sure like 您可以使用IF NOT EXISTS标记来确定

  CREATE TABLE IF NOT EXISTS". $file_name . "(
  1. make sure that the variable $file_name is not empty. 确保变量$file_name不为空。 Else, you are passing a null identifier in CREATE TABLE statement; 否则,您在CREATE TABLE语句中传递了一个空标识符。 which will not succeed. 这不会成功。

Per your comment: you have $file_name = 'currentScan.csv'; 根据您的评论:您有$file_name = 'currentScan.csv';

That's the problem here. 这就是这里的问题。 You are trying to create a table named currentScan.csv which your DB engine thinking that currentscan is the DB name and .csv is the table name which obviously doesn't exits and so the error. 您正在尝试创建一个名为currentScan.csv的表,您的数据库引擎认为currentscan是该数据库的名称,而.csv是该表的名称,显然该表不会退出,因此出现错误。

first check your database connection and change your query with given below : 首先检查您的数据库连接并使用以下给定的条件更改查询:

$sqlTableCreate = "CREATE TABLE ". $file_name . " ( 
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM