我正在尝试连接数据库,但遇到错误:无效的数据源名称
我正在使用PDO与数据库adapter.php中的建立连接。带有模型类中有关主机,用户名和密码的变量。
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";
}
}
model.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();
}
}
谢谢您的帮助
答案 0 :(得分:0)
这是一个错字。
$this->$connectionString= $connectionString;
$this->$username= $username;
$this->$password= $password;
应该是
$this->connectionString = $connectionString;
$this->username = $username;
$this->password = $password;