phpmysqlpdotry-catch

PDO connection doesn't return error when specified user doesn't exist


I'm developing a configuration interface where the client has to specify the db parameters (host, user, password, db).

try{
  $c = new PDO('mysql:host='.$_POST['database_host'].';charset=utf-8', $_POST['database_user'], $_POST['database_password']);
  $c->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
  $c->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ);
  $c->query("USE `".$_POST['database']."`;");
}
catch(Exception $e)
{
    if(strstr($e->getMessage(),"[1045] Access denied for user '".$_POST['database_user']."'@'".$_POST['database_host']."' (using password: NO)"))
    {
        $errors[] = "This user requires a password.";
        $fields['database_password']['valid'] = false;
    }
    else if(strstr($e->getMessage(),"[1045] Access denied for user '".$_POST['database_user']."'@'".$_POST['database_host']."' (using password: YES)"))
    {
        $errors[] = "Wrong password or unexisting user.";
        $fields['database_password']['valid'] = false;
        $fields['database_user']['valid'] = false;
    }
    else echo $e->getMessage();
}

If I enter an existing user with wrong or no password the error is caught (the errors message is displayed "This user requires a password." or "Wrong password or unexisting user."). But if I enter an unexisting user there is no error thrown just a warning

Warning: PDO::query(): SQLSTATE[42000]: Syntax error or access violation: 1044 Access denied for user ''@'localhost' to database 'mediatheque' in C:\wamp\www\mediatheque3\index.php on line 425

and the script goes on I have no idea how to stop it and notify the user about the wrong username.

How should I handle that problem ? Thank you.


Solution

  • Well it makes sense because you set the ERRMODE_EXCEPTION after creating the connection object so its too late.

    Solution is to pass the attribute to the PDO constructor :

    $attribute = array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ
    );
    $c = new PDO('mysql:host='.$_POST['database_host'].';charset=utf-8',
                               $_POST['database_user'], $_POST['database_password'], 
                               $attribute);