简体   繁体   中英

Run multiple CREATE TABLe queries with MySQL and PHP

I need to create a large number of tables at once and add data to the first one using PHP and MySQL. My code looks like this:

$sql = "CREATE TABLE table1 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";

//adding businesses to table
$sql .= "INSERT INTO table1 (code, name)
VALUES ('CODE', 'name');";
//^this basic idea is run a few more times

$sql .= "CREATE TABLE table2 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//^same basic thing run a bunch more times w/ variations to columns

if ($conn->multi_query($sql) === TRUE) {
echo "<p>Tables created.</p>
<a href=\"adduser_form.php\">Continue</a>";
} else {
    echo "<p>Error creating tables: " . $conn->error . "</p>";
}

This only creates the first table and adds the data to it, it won't create any other tables and I get no error messages (the success message is shown). I've been googling a solution for an hour and I can't come up with anything. I'm thinking I need a way to hold off creating the next table until the previous one has been created?

I'm very new to MySQL so newbie-friendly would be very much appreciated:)

Try using backticks in your SQL statements, such as:

$sql .= "CREATE TABLE `table2` (
    `code` VARCHAR(5) PRIMARY KEY,
    `name` VARCHAR(50) NOT NULL
);";

You should also use backticks in your INSERT statement (and your first CREATE query).

If I'm not mistaken, name is reserved word.

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