简体   繁体   中英

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.

For one, this

'CREATE TABLE $table'

will NOT fill in $table, but will be LITERALLY

CREATE TABLE $table

use " if you want variables to be shown. You would've spotted that if you'd just echo your $sql . There might be more, but probably easily discoverable trough mentioned debugging...

1

change the single quotes (') to double quotes (") for your query.

2

or use dot operator (.) to append php variable.

$tableName = "mytable";
echo $query1 = "SELECT * FROM $tableName";
echo $query2 = 'SELECT * FROM $tableName';

// Output

SELECT * FROM mytable

SELECT * FROM $tableName

You apparenty have an extra trailing comma:

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

You may have VARCHAR field entered without size like fieldname VARCHAR will return error instead it should be like fieldname VARCHAR(100) ? Trailing comma may also be the reason for error as Quassnoi commented.

If you are trying to get rid of the trailing slash you can also do this by using a counter.

$fieldsCount = count($listingFields);
foreach($listingFields as $key => $listing)
{ // create the insert statement (do not add comma at the end)
    $query .=" ".$listing[0];
    if ( $key+1 != $fieldsCount )
    {
        $query .=',';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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