0

I get the following error since I upgrade to PHP 7: "Fatal error: Uncaught Error: Call to a member function prepare() on null".

Here is my code:

class Database {
private $host = "localhost";
private $user = "xxx";
private $pass = "xxxx";
private $dbname = "xxxxx";
private $stmt;
private $dbh;
private $error;

public function __construct($dbname){
    // Set DSN
    $this->dbname = $dbname;
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;      
    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND  => 'SET sql_mode="ALLOW_INVALID_DATES"'
    );
    // Create a new PDO instance
    try{
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}
public function query($query){
    $this->stmt = $this->dbh->prepare($query);
}
.......
}

How do I solve it? Thank you in advance.

JLR
  • 11
  • 1
  • 1
    If `$this->dbh` is null, have you checked `$this->error`? – rickdenhaan Jan 06 '18 at 22:41
  • You catch any errors but don't know how to treat them :( – Chay22 Jan 06 '18 at 22:42
  • have you checked $this->error? Its only tells me that the error in the line "$this->stmt = $this->dbh->prepare($query);". Chay22 I am a newbie, I am in the learning process. – JLR Jan 06 '18 at 23:01
  • @JLR That's not what I meant. The error you're seeing is that you're doing `$this->dbh->prepare()`, but `$this->dbh` is null. In your constructor you define `$this->dbh` to be a new PDO connection, but if that fails you catch the error and store the reason that fails in the `$this->error` property (and then continue as if it worked anyway). So for debugging, you need to output `$this->error` to see why you couldn't create a new PDO connection. – rickdenhaan Jan 07 '18 at 14:25
  • Thanks rickdenhaan for taking the time to explain this to me. I edited my code an I get a "SQLSTATE[HY000] [2002] No such file or directory". So, the problem is when is trying to connect to MySQL. Now I have a clue. – JLR Jan 08 '18 at 11:02

0 Answers0