php - 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();
}
}
谢谢您的帮助
解决方案
这是一个错字。
$this->$connectionString= $connectionString;
$this->$username= $username;
$this->$password= $password;
应该
$this->connectionString = $connectionString;
$this->username = $username;
$this->password = $password;
推荐阅读
- r - 在 R 中绘制所有日期的控制图
- r - 使用 R 选择具有相同基本名称的文件
- image - QML Qt 图像不在 .exe 文件中
- appium - 尝试通过 Appium 运行我的第一个 ruby 测试
- c++ - 是否参考右值
- excel - 如何锁定excel宏(VB代码)
- hyperledger - HyperledgerComposer:我如何从颁发的身份创建 BusinessNetwork 卡?
- reactjs - 在 React 之外维护状态和“用新的根组件替换 React 渲染的子组件”。警告
- c - 为什么我得到数组元素的位置而不是它的值?C
- regex - Perl 正则表达式 - 删除点分隔字符串的第一部分