daveh / php-mvc

A simple PHP model-view-controller framework, built step-by-step as part of the "Write PHP like a pro: build an MVC framework from scratch" course on Udemy.
https://davehollingworth.com/go/phpmvc/
MIT License
782 stars 311 forks source link

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\joblister\lib\Database.php:32 Stack trace: #0 C:\xampp\htdocs\joblister\lib\job.php(10): Database->query('SELECT jobs.*, ...') #1 C:\xampp\htdocs\joblister\index.php(15): Job->getAllJobs() #2 {main} thrown in C:\xampp\htdocs\joblister\lib\Database.php on line 32 #114

Open codesmith445 opened 1 year ago

codesmith445 commented 1 year ago

<?php class Database { private $host = DB_HOST; private $user = DB_USER; private $pass = DB_PASS; private $dbname = DB_NAME;

private $dbh;
private $error;
private $stmt;

public function __construct() {
    // Set DSN
    $dsn = 'mysql:host='. $this->host .';dbname='. $this->dbname;

    // Set Options
    $options = array (
       PDO::ATTR_PERSISTENT => true,
       PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );

    //PDO INSTANCE
    try {
      $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    } catch(PDOException $e) {
        $this->error = $e->getMessage();

    }
}

public function query($query) {
    $this->stmt = $this->dbh->prepare($query);
}

public function bind($param, $value, $type = null) {
   if(is_null($type)) {
    switch(true) {
        case is_int ( $value ) :
            $type = PDO::PARAM_INT;
            break;
        case is_bool ( $value ) :
            $type = PDO::PARAM_BOOL;
            break;
        case is_null ( $value ) :
            $type = PDO::PARAM_NULL;
            break;
        default :
        $type = PDO::PARAM_STR;
    }
   }
   $this->stmt->bindValue($param, $value, $type);
}
public function execute() {
    return $this->stmt->execute();
}
public function resultSet() {
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}

public function single() {
    return $this->stmt->fetch(PDO::FETCH_OBJ);
}

}

daveh commented 1 year ago

The error message is saying $this->dbh is null - this happens when it hasn't connected for some reason, probably because of incorrect database credentials (user, password)