PDO连接失败

时间:2015-04-03 08:10:24

标签: pdo

这是我的数据库连接代码,因为我不打算把它放在它工作的类中的函数中,但如果它的内部函数没有任何想法吗?

class DBConnection {

private $connection;

function __construct(){
  $this->open_connection();
}

public static function open_connection(){

  try {
      $connection = new PDO('mysql:host=localhost;dbname=practice','root','');
      $connection->exec("SET NAMES 'utf8'");
      $connection->exec("SET CHARACTER SET utf8");
      $connection->exec("SET character_set_server=utf8");
      $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      return $connection;

  } catch (Exception $e) {
    die($e->getMesage());

  }

}

}// class ends

1 个答案:

答案 0 :(得分:0)

我认为你的代码中的问题是你使用静态函数来返回连接而你的构造函数没有赋给你私有变量

私有$连接的第一个解决方案:

class DBConnection {

private $connection;

function __construct(){
  $this->connection = $this->open_connection();
}

public static function open_connection(){

  try {
      $connection = new PDO('mysql:host=localhost;dbname=practice','root','');
      $connection->exec("SET NAMES 'utf8'");
      $connection->exec("SET CHARACTER SET utf8");
      $connection->exec("SET character_set_server=utf8");
      $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      return $connection;

  } catch (Exception $e) {
    die($e->getMesage());

  }

}

带有连接静态的借调

class DBConnection {

private static $connection = null;

function __construct(){
  if (self::$connection == null) 
        $this->open_connection();
}

public static function open_connection(){

  try {
      self::$connection = new PDO('mysql:host=localhost;dbname=practice','root','');
      self::$connection->exec("SET NAMES 'utf8'");
      self::$connection->exec("SET CHARACTER SET utf8");
      self::$connection->exec("SET character_set_server=utf8");
      self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  } catch (Exception $e) {
    die($e->getMesage());

  }

}

我希望能帮助你。