Saturday 17 June 2017

php - I can't find what *exactly* the syntax error is in mysql





I am creating a simple database and it's table for learning purpose:



This is my php code(script.php)




$sql = file_get_contents("init.sql");

$servername = "localhost";
$username = "root";

$password = "";
// connect to database
$conn = new mysqli($servername, $username, $password);

if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}


if($conn->query($sql) == True){

echo "Database and Table has been created succesfully!";
}

else {
echo "\nError creating database and table: . $conn->error";
}

?>



And this is mysql file(init.mysql)



CREATE DATABASE test;
USE test;

CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),

date_of_registration TIMESTAMP)


The exact error I am seeing is:-




Error creating database and table: . You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'USE test; CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY ' at line 2




In my opinion, the code is syntactically correct but as you see I am getting an error

So I am struggling to find where is the error but no luck :(
Or I am blind enough to see it.


Answer



To process multiple queries in one call (you have three in your file), you need to use multi_query. Change



if($conn->query($sql) == True){


to




if($conn->multi_query($sql) == True){

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...