I'm trying to create a mysql user account at runtime in PHP7.0, granted access to a single database, also created at runtime. I'm currently using:
$this->mysqli = new mysqli('localhost', $admin_account, $password);
$setup = [
/* create database */
sprintf('CREATE DATABASE IF NOT EXISTS %s;', $dbName),
/* grant admin */
sprintf("GRANT ALL PRIVILEGES ON %s.* TO '%s'@'%s' WITH GRANT OPTION;", $dbName, $admin_account, $admins_remote_ip),
/* add user */
sprintf("CREATE USER '%s'@'localhost' IDENTIFIED BY '%s';", $dbUsername, $dbPassword),
/* THIS WAS ADDED AS A FIX TO NO AVAIL */
sprintf("UPDATE mysql.user SET password=PASSWORD('%s') WHERE user='%s'", $dbPassword, $dbUsername),
/* grant retailer*/
sprintf("GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost';", $dbName, $dbUsername),
/* flush */
"FLUSH PRIVILEGES;",
];
foreach ($setup as $query) {
if (false == $this->mysqli->query($query)) {
$error = $this->mysqli->error;
return $error;
}
}
All of the statements execute without an error, everything appears to be where it should, however the non-admin user gets a mysql->error;
Connect failed: Access denied for user 'dbUsername'@'localhost' (using password: YES)
If I do this;
> mysql -u admin_account -p
update mysql.user set password=PASSWORD('dbPassword') where user='dbUsername';
Then the connection works and all is well. Please help.
*edit: I've removed the transactional behaviour, removing it from the live code didn't fix the issue. It appears that the password string is being altered somewhere between PHP and MySQL?
mysqlireturns any error messages?UPDATE mysql.user …statement supposed to be good for? The one above that,CREATE USER … IDENTIFIED BY 'password'should have already set that password for the user when it was created …?mysqli_real_escape_string. Also note that you can perform the grant in a single query:GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'will create the user, grant access and set the password all in one go.