lefty55104 lefty55104 - 1 month ago 18
PHP Question

Create mysql table from PHP array

A user is creating a table. The user enters the number of fields that will be in the table, and a form is generated based on the number they entered. They then enter the names of the columns and the type. I then create the table based on what they entered.

I can get the arrays to populate correctly, but my error message says I have a syntax error. I'm sure I did something wrong, but I tried to add a while loop inside the query since there is no set number of variables to be entered. This is what I have. If there's a better way to do it, I'm all ears.

$sql = 'CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id), ';

while($numDone < $totalFields){
$sql .= $colName[$x] . ' ' . $types[$x] . ', ';
$x++;
$numDone++;
}
$sql .= ')';
$query1 = mysql_query($sql) or die(mysql_error());


**Solved
I changed the single quotes to double quotes, used the dot operator for $table, and added an if statement for the comma. It's working now.

Answer

You apparenty have an extra trailing comma:

CREATE TABLE $table (
       id INT NOT NULL AUTO_INCREMENT,
       PRIMARY KEY(id),
       col1 INT,
       col2 INT,
--             ^ here
       )