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

xesrikrc  于 2023-08-02  发布在  Mysql
关注(0)|答案(1)|浏览(99)

我正在学习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


请告诉我该如何解决这个问题。我是新来的,并遵循在线教程,所以请帮助我纠正这个问题。任何帮助都将不胜感激

gzszwxb4

gzszwxb41#

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

    }
}

字符串

相关问题