简体   繁体   中英

PHP PDO Create MySQL database and user and grant privileges

I have this php function:

function createDatabase($dbName,$dbPass) {
         $host = 'localhost';
         $user = 'myuser';
         $user_password = 'mypass';
         $db = new PDO("mysql:host=$host", $user, $user_password);
         $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
         try {
           doLog('Creating Database...');
           $count = $db->exec("CREATE DATABASE `$dbName`");
           if($count === false) {
             doLog('Could not create database');
             return false;
           }
           doLog('Creating User...');
           $count = $db->exec("CREATE USER '$dbName'@'localhost' IDENTIFIED BY '$dbPass'");
           if($count === false) {
             doLog('Could not create user');
             return false;
           }
           doLog('Granting User Privileges...');
           $count = $db->exec("GRANT ALL ON `$dbName`.* TO '$dbName'@'localhost'");
           if($count === false) {
             doLog('Could not grant user privileges');
             return false;
           }
           doLog('Flushing Privileges...');
           $count = $db->exec("FLUSH PRIVILEGES");
           if($count === false) {
             doLog('Could not flush privileges');
             return false;
           }

         } catch (PDOException $e) {
           doLog("DB ERROR: ". $e->getMessage());
           return false;
         }
         return true;
    }

I was working off another question here: Can I create a database using PDO in PHP

This code keeps getting hung up during the 3rd query with granting privileges with this error:

SQLSTATE[42000]: Syntax error or access violation: 1044 Access denied for user

The MySQL user in question has global permissions, including grant. What else could I be missing?

The MySQL user in question has global permissions, including grant. What else could I be missing?

Noting but common sense.

If your database says the a user has not permissions then it is so.

This is the point of error messages: yo have to read them and fix them. As simple as that.

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