0
votes

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.

1
Error tells you that you have wrong login and password. Have you checked them? - u_mulder
You have entered wrong DB credentials. - Ravi
Your db name is in self::$data['db'], in dsn string you use self::$data['name']. Are you sure? - u_mulder
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. - Your Common Sense
new PDO($dsn, $username, $password); Only a few database types support a username and password in the $dsn itself. - Xorifelse

1 Answers

0
votes
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());
        }
    }
}