mysql创建动态表[关闭]

I am trying to create a table dynamically and the only problem I am facing is that creating the columns dynamically. I mean like I won't have fixed number of columns so I tried representing it as a variable but when I run the code it gives me an error. The below is what I tried.

the error

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();

This is essentially what should work:

$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(",
",$colArray);

$sql = "CREATE TABLE IF NOT EXISTS {$table_name}(
{$columns},
PRIMARY KEY (id))";
 $stmt = $db->prepare($sql);
 echo $db->error;
 $stmt->execute();