0

This is the first time that i will ask a question in this forum.

I am working on a php project in which i have to -through php- create a database and insert some empty tables.

The issue here is that i always get an error message regarding syntax when i try to add privileges to the superuser (for some reason, if i don't, an error message states that i don't have permition to access the database).

Here is the code for creating the database and assigning privileges:

$sql = "CREATE DATABASE IF NOT EXISTS `database` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; "; 

$sql .= "GRANT SELECT database.* TO 'superuser'@'localhost' ";

$sql .= "GRANT ALL ON database." TO 'superuser'@'localhost' IDENTIFIED BY 'password'; ";

$sql .= "FLUSH PRIVILEGES"; 

Can you tell me what did wrong? Thanks in advance!

1
  • 1
    Most database libraries allow only one query at a time Commented Nov 9, 2013 at 17:14

1 Answer 1

1

You need to end each of your SQL statements with a semi colon ;, it is missing after the first GRANT. The second GRANT uses database." and should be database.*, should also be surrounded by backticks as "database" is a reserved word. That said, the first GRANT can be omitted as the it will be included with GRANT ALL.

$sql = "CREATE DATABASE IF NOT EXISTS `database` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; ";
$sql .= "GRANT ALL ON `database`.* TO 'superuser'@'localhost' IDENTIFIED BY 'password'; ";
$sql .= "FLUSH PRIVILEGES;"; 

You can also use a HEREDOC format to make it easier to read

$sql = <<<SQL
  CREATE DATABASE IF NOT EXISTS `database` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
  GRANT ALL ON `database`.* TO 'superuser'@'localhost' IDENTIFIED BY 'password';
  FLUSH PRIVILEGES; 
SQL;
Sign up to request clarification or add additional context in comments.

8 Comments

There is one missing after your first GRANT statement
when i add the semicolon, i get an error message tha the query has failed
Please see my last edits, there were actually several errors in your example.
$sql = <<<SQL CREATE DATABASE IF NOT EXISTS 'strongim_$this->title' DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; GRANT ALL ON 'strongim_pmsimple_$this->title'.* TO 'DB_USER'@'DB_SERVER' IDENTIFIED BY 'DB_PASS'; FLUSH PRIVILEGES; SQL;
DB_USER, DB_SERVER and DB_PASS are defined variables
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.