Search code examples
phpmysqlpdo

PDO access denied for user 'username'@'%'


I need to connect to a remote mysql server using a php page;
the connection itself works as a charm, but the moment i try to create the database, as it doesn't exist yet, i get this error:

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1044 Access denied for user '[myusername]'@'%' to database '[mydbname]'' in [myurl]/php/db_manager.php:76

As you can see, i have access denied to "%".
Now: what is "%"?

Furthermore:

Main file

private function createDB() {
if($this->cm->update("CREATE DATABASE IF NOT EXISTS " . $this->dbName . " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;", array())) { // Error here
  $this->cm->update("USE " . $this->dbName . ";", array());
  return true;
}
return false;
}

$this->cm is an instance of a correctly initialized PDO wrapper

PDO wrapper file

public function update($query, $values) 
try{
        $sql = $this->db->prepare($query);
        $sql->execute($values);
        return true;
    } catch(PDOException $e) {
        $this->l->error($e); // <- Error here
        return false;
    }
}

$this->db is a correctly instantiated, fully connected PDO object;
These are the lines used to connect

$this->db = new PDO($connection, $this->db_user, $this->db_password, array(PDO::ATTR_PERSISTENT => true));
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I have full access on the Mysql server


Solution

  • Access denied for user '[myusername]'@'%' to database '[mydbname]'

    MySQL permissions are granular: not all users have full access to all databases on the server.

    You need to sign in with an administrator and grant the appropriate permissions. For instance, to grant full access:

    GRANT ALL
    ON mydbname.*
    TO 'myusername'@'%'
    WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    

    ... or you can be more selective to your liking:

    GRANT SELECT, ALTER, CREATE, DELETE, DROP, INDEX, INSERT, REFERENCES, TRIGGER, UPDATE
    ON mydbname.*
    TO 'myusername'@'%';
    FLUSH PRIVILEGES;
    

    Please check Privileges Supported by MySQL for a full list.

    % is a wildcard explained in detail at Account Names and Passwords that means "connection from any host".