使用PDO建立与localhost数据库的连接问题

时间:2016-06-16 01:02:27

标签: php mysql pdo

我正在学习PHP并尝试与我的数据库建立连接,这样我就可以进行简单的数据输入/输出。我正在学习面向对象的PHP。我有一个index.php调用database.php文件。 database.php文件包含所有连接材料。数据库已在我的localhost上创建。我正在尝试连接它。使用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 个答案:

答案 0 :(得分:0)

使用此代码:如果要升级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;

    }
}