创建PDO实例会导致错误

时间:2016-10-01 22:29:23

标签: php mysql pdo

我正在尝试使用PDO连接到mysql,但是当我尝试创建PDO的实例时,它会导致代码中断。我试过把它放进去尝试并捕获,但它仍然打破代码/我得到一个页面说“本地主页不起作用”

protected $conn;

$dsn = "mysql:host=localhost;dbname=Mydatabase";
$this->conn = new PDO($dsn, "admin", "test2016");

如果我尝试连接到这样的mysql:

$conn = mysqli_connect("localhost", "admin", "test2016");

它工作正常。

我不确定为什么新的PDO会导致该错误。

class Database {

protected $conn;

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

function init(){
   try{
    $this->conn= $this->connectDB("localhost","Mydatabase","admin","test2016"); // the here
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
   }catch(PDOException $e){
      echo "Connection failed: " . $e->getMessage();
    }

}

function connectDB($servername,$database,$username,$password){

   $dsn = "mysql:host=localhost;dbname=Mydatabase";
   return new PDO($dsn, $username, $password);// i am not sure why new pdo is the cause of the problem

   // $conn = mysqli_connect($servername, $username, $password);

    //if (!$conn) {
      // die("Connection failed: " . mysqli_connect_error());
    //}

    //echo "Connected successfully";

}

2 个答案:

答案 0 :(得分:0)

根据您的编辑,您尝试在未定义的变量上调用方法:

function init(){
   try{
     $this->conn= $this->connectDB("localhost","Mydatabase","admin","test2016"); // the here
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

应该是:

function init(){
   try{
     $this->conn= $this->connectDB("localhost","Mydatabase","admin","test2016"); // the here
     $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     ^^^^^ here

答案 1 :(得分:-2)

这是一个非常基本的例子,适用于你想要做的事情。

class Database {

    protected $conn;

    public function __construct() {
        $this->init();
    }

    public function init() {
        try{
            $this->conn = $this->connectDB("localhost","Mydatabase","admin","test2016");
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            if (!$this->conn) {
                throw new Exception("Connection failed: ");
            }
            echo 'Connected';
        } catch (PDOException $e) {
            die($e->getMessage());
        }
    }

    public function connectDB($servername, $database, $username, $password) {
        $dsn = "mysql:host=".$servername.";dbname=".$database;
        return new PDO($dsn, $username, $password);
    }

}

如果此课程不适合您,请测试您的服务器信息,甚至服务器状态。

我希望这对你有所帮助。