首页 > 解决方案 > PHP PDO 无效的数据源名称

问题描述

我正在尝试连接到数据库但遇到错误: 无效的数据源名称

在文件 adapter.php 中,我使用 PDO 连接到数据库。使用模型类中关于主机、用户名、密码的变量。

    class Adapter{
    private $connectionString;
    private $username;
    private $password;
    private $conn;

    public function __construct($connectionString, $username, $password){
        $this->$connectionString= $connectionString;
        $this->$username= $username;
        $this->$password= $password;
    }

    public function dbConnect(){ 
        try{

            $this->conn = new PDO($this->connectionString, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            echo "Connected successfully"; 

        }catch(PDOException $e){
            echo "Connection failed: " . $e->getMessage();
            $this->conn=null;
        }  
    }

    public function dbClose(){
        $this->conn = null;
        echo "Closed successfully";
    }

}

模型.php

    define 
 ('DB_CONNECTION_STRING',"mysql:dbname=vnguye24_movieDB;host=127.0.0.1");
    define('DB_USER',"root");
    define('DB_PASSWORD',"root");

    class Model{
    private $dbadapter;


    public function __construct(){
        $this->dbadapter = new Adapter(DB_CONNECTION_STRING,DB_USER,DB_PASSWORD);

    }

    public function runDB(){
        $this->dbadapter->dbConnect(); 
    }


}

谢谢您的帮助

标签: php

解决方案


这是一个错字。

$this->$connectionString= $connectionString;
$this->$username= $username;
$this->$password= $password;

应该

$this->connectionString = $connectionString;
$this->username = $username;
$this->password = $password;

推荐阅读