[英]issue establishing connection to localhost database using PDO
我正在學習PHP,並嘗試與數據庫建立連接,以便可以進行簡單的數據輸入/輸出。 我正在學習面向對象的PHP。 我有一個index.php,它調用了database.php文件。 database.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
請告訴我我該如何解決。 我是新手,正在關注在線教程,因此請幫助我解決此問題。 任何幫助將被申請
請使用以下代碼:如果您想升級PDO類。BaseDao{
protected $user="root";
protected $pass="";
protected $name="mydatabase";
protected $dbh=null;
function openConn(){
$this->dbh=new PDO("mysql:host=localhost;dbname=".$this->name,$this->user,$this->pass);
}
function closeConn(){
$this->dbh=null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.