This question already has an answer here:
I am trying to create a mySQL table with php and I am getting a syntax error whenever I run my code. The string is
$sql = "DROP TABLE Colors;
CREATE TABLE Colors (
color VARCHAR(30) NOT NULL,
vote INT(16) NOT NULL UNSIGNED,
hex VARCHAR(10) NOT NULL,
PRIMARY KEY (color)
)";
query line is ($conn is the connection to the server)
$conn->query($sql)
The error is
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'CREATE TABLE Colors (
color VARCHAR(30) NOT NULL,
vote INT(16) NOT NULL UNSIGNED' at line 2
Does anyone see what I am doing wrong?
</div>
Not sure which mysql lib you are using, but in PHP you should use function multi_query in your scenario.
$sql = "DROP TABLE Colors;
CREATE TABLE Colors (
color VARCHAR(30) NOT NULL,
vote INT(16) NOT NULL UNSIGNED,
hex VARCHAR(10) NOT NULL,
PRIMARY KEY (color)
)";
mysqli_multi_query($conn, $sql);
You need to execute one statement at a time. ;
is a construct used by the command-line tool as a delimiter, it's not actually used in the MySQL protocol for communicating so it's an error. The DELIMITER
value can also be changed.
Split up it looks like this:
$conn->query("DROP TABLE Colors");
$conn->query("CREATE TABLE ...");
Note, I strongly encourage you to do proper error checking here and have exceptions turned on so that if a statement fails you know about it.