Fatal error: Call to undefined method Database::prepare()

前端 未结 3 1044
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 18:28

I have created a separate class for database and users.

Database.php

 class Database{

     private $db;


    public function __construct(){

  /***         


        
3条回答
  •  -上瘾入骨i
    2020-12-03 19:21

    You create $dbh when you instantiate Database(), but instantiating the Database only returns an instance of your Database class, not your db connection. You should have a getDb to get your connection from database object:

    $dbClass = new Database();
    $dbh = $dbClass->getDb(); // here you get the connection
    $users= new Users($dbh);  // here you give to Users() the $dbh, that isn't your 
                              // connection.. it's just Database class
    

    Database construct only return an instance of your Database class, not your db connection

    class Database{
    
     private $db;
    
    
    public function __construct(){
    
        try {
         $this->db = new PDO("mysql:host=$hostname;dbname=kamadhenu_web", $username, $password);
        /*** echo a message saying we have connected ***/
    
       }
        catch(PDOException $e)
            {
                echo $e->getMessage();
           }    
     }
    
     public function getDb() {
           if ($this->db instanceof PDO) {
                return $this->db;
           }
     }
    
    
    }
    

提交回复
热议问题