我正在学习PHP,并试图与我的数据库建立连接,这样我就可以做简单的数据输入/输出。我正在学习面向对象的PHP。我有一个index.php,它调用database.php文件。php文件包含所有连接材料。数据库已在我的本地主机上创建。我试图连接到它。使用PDO。
database.php文件代码为:
<?php
class Database{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $dbname = 'edunoix';
private $dbh;
private $error;
private $stmt;
public function __construct(){
//dsn or connection string
$dsn = 'myql:host='. $this->$host . ';dbname=' . $this->dbname;
//set pdo options
$options = array(
PDO::ATTR_PERSISTENT =>true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
//create a new pdo
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}catch(PDOEception $e){
$this->error = $e->getMessage();
}
}
}
?>
字符串
当我编译和运行时,我会得到以下错误:
( ! ) Notice: Undefined variable: host in C:\wamp\www\oophp\pdo\classes\Database.php on line 16
Call Stack
# Time Memory Function Location
1 0.0005 237960 {main}( ) ..\index.php:0
2 0.0010 247584 Database->__construct( ) ..\index.php:5
( ! ) Fatal error: Cannot access empty property in C:\wamp\www\oophp\pdo\classes\Database.php on line 16
Call Stack
# Time Memory Function Location
1 0.0005 237960 {main}( ) ..\index.php:0
2 0.0010 247584 Database->__construct( ) ..\index.php:5
型
请告诉我该如何解决这个问题。我是新来的,并遵循在线教程,所以请帮助我纠正这个问题。任何帮助都将不胜感激
1条答案
按热度按时间gzszwxb41#
使用此代码:如果你想升级你的PDO类.BaseDao{
字符串