-2

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

This is my php code(script.php)

<?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.

dave
  • 191
  • 1
  • 7
  • 2
    `mysqli_query` can't do multiple statements iirc? – Jonnix Jan 07 '19 at 12:45
  • 1
    You can't run more than one query at a time unless you use mysqli_multi_query(). Each statement terminated by a semi-colon is a query. So you are trying to execute three at a time. – John Conde Jan 07 '19 at 12:45
  • Seems like the library cannot execute more than one query (separated by `;`)... remove the `use db;` part. – Salman A Jan 07 '19 at 12:45
  • You can use (SqlFiddle)[http://sqlfiddle.com/#!9/a1b300/1] to play around and learn without having to step through PHP all the time. – LosManos Jan 07 '19 at 12:52
  • @JohnConde Yeah, Now I realised, but at _that_ time I didn't really think about it and all I was starting was my SQL code which has no syntax error as you can see – dave Jan 07 '19 at 15:55

1 Answers1

6

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){
Nick
  • 138,499
  • 22
  • 57
  • 95