我正在尝试动态创建一个表,我面临的唯一问题是动态创建列。我的意思是,我不会有固定数量的列,所以我尝试将其表示为变量,但是当我运行代码时,它给了我一个错误。以下是我的尝试。
错误
You have an error in your SQL syntax; check the manual that corresponds to your...
$colArray = array();
foreach($ml as $df){
$colArray[] = "`".$df."` VARCHAR(250) NOT NULL,<br/>";
}
$columns = implode("",$colArray);
$sql = "CREATE TABLE IF NOT EXISTS {$table_name}(
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(250) NOT NULL,
{$columns}
date VARCHAR(250) NOT NULL,
PRIMARY KEY (id)
)";
$stmt = $db->prepare($sql);
echo $db->error;
$stmt->execute();
答案 0 :(得分:0)
这基本上应该起作用:
$colArray = array();
// Since you want these two columns in order
// assign here
$colArray[] = "id INT NOT NULL AUTO_INCREMENT";
$colArray[] = "username VARCHAR(250) NOT NULL";
foreach($ml as $df) {
$colArray[] = "`".$df."` VARCHAR(250) NOT NULL";
}
// Since you want column last, assign here
$colArray[] = "date VARCHAR(250) NOT NULL";
$columns = implode(",\r\n",$colArray);
$sql = "CREATE TABLE IF NOT EXISTS {$table_name}(
{$columns},
PRIMARY KEY (id))";
$stmt = $db->prepare($sql);
echo $db->error;
$stmt->execute();