0

Good day, 2 weeks ago I used Mysqli and everything was ok, but now I use PDO and have many problems. It's one of them. I used next settings for connect to MySQL in MYSQLi class:

self::$data['host'] = 'localhost';
self::$data['user'] = 'mysql';
self::$data['pass'] = 'mysql';
self::$data['db']   = '123';

And it worked. But when I used it in this:

private static function connect()
    {
        if(!self::$connection)
        {
            try
            {
                self::$connection = new \PDO('mysql:host='.self::$data['host'].';dbname='.self::$data['name'], self::$data['user'], self::$data['pass']);
                self::$connection -> setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                self::$connection -> exec('SET NAMES utf8');
            }
            catch (PDOException $e)
            {
                die('Ошибка подключения к БД: '.$e->getMessage());
            }
        }
    }

PHP call error:

SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO)

I'm sorry, I'm a beginner in PDO.

6
  • 1
    Error tells you that you have wrong login and password. Have you checked them?
    – u_mulder
    Jan 31, 2016 at 9:23
  • You have entered wrong DB credentials. Jan 31, 2016 at 9:25
  • 2
    Your db name is in self::$data['db'], in dsn string you use self::$data['name']. Are you sure?
    – u_mulder
    Jan 31, 2016 at 9:27
  • Your connection code is wrong. Please read how to connect properly and why you shouldn't catch. With proper error reporting you would have been able to spot that silly typo yourself. Jan 31, 2016 at 9:53
  • new PDO($dsn, $username, $password); Only a few database types support a username and password in the $dsn itself.
    – Xorifelse
    Jan 31, 2016 at 14:04

1 Answer 1

0
self::$data['host'] = 'localhost';
self::$data['user'] = 'mysql';
self::$data['pass'] = 'mysql';
self::$data['db']   = '123';

private static function connect()
{
    if(!self::$connection)
    {
       try
       {
          self::$connection = new PDO('mysql:host='.self::$data['host'].';dbname='.self::$data['db'], self::$data['user'], self::$data['pass']);
            // just correct your database name variable like as above
            self::$connection -> setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            self::$connection -> exec('SET NAMES utf8');
        }
        catch (PDOException $e)
        {
            die('Ошибка подключения к БД: '.$e->getMessage());
        }
    }
}
1
  • Thanks. Your comment is very useful
    – LittleByte
    Feb 3, 2016 at 17:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.