简体   繁体   English

使用PDO建立与本地主机数据库的连接的问题

[英]issue establishing connection to localhost database using PDO

I am learning PHP and trying to establish a connection with my database so i can do simple data input/output. 我正在学习PHP,并尝试与数据库建立连接,以便可以进行简单的数据输入/输出。 I am learning object oriented PHP. 我正在学习面向对象的PHP。 I have an index.php which calls the database.php file. 我有一个index.php,它调用了database.php文件。 The database.php file has all the connection material. database.php文件包含所有连接材料。 The database has been created on my localhost. 该数据库已在我的本地主机上创建。 I am trying to connect to it. 我正在尝试连接到它。 Using the PDO . 使用PDO。

The code in the database.php file is : 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();
        }
    }
}

?>

When i compile and run i get the following error: 当我编译并运行时,出现以下错误:

   ( ! ) 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

Please tell me how can i resolve this. 请告诉我我该如何解决。 I am new and following an online tutorial so please help me correct the issue. 我是新手,正在关注在线教程,因此请帮助我解决此问题。 Any help will be appriciated 任何帮助将被申请

use this code: if you want to upgrade your PDO class.BaseDao{ 请使用以下代码:如果您想升级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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM