如何在PHP中连接到PDO

时间:2016-01-31 09:20:32

标签: php mysql pdo

美好的一天,2周前我使用了Mysqli,一切都很好,但现在我使用PDO并且遇到很多问题。这是其中之一。我在MYSQLi类中使用了下一个连接到MySQL的设置:

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['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调用错误:

  

SQLSTATE [HY000] [1045]用户''@ localhost'拒绝访问(使用密码:否)

对不起,我是PDO的初学者。

1 个答案:

答案 0 :(得分: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());
        }
    }
}