ajMad88
ajMad88

Reputation: 1

PHP "Fatal Error: Call to a member function prepare() on null" Error thrown on PHP PDO block of code

For some reason I keep getting this error. This code is modeled after a recent project I did. I made sure that all of my code is specific to this project and not the other. I think it has something to do with my db_connect.php but I don't know what, I figured another set of eyes on it would help.

This is the block it throws the error on

<?php
class CRUD
{
  private $Db;
  function _construct($DB_CON)
  {
    $this->Db = $DB_CON;
  }
public function getUserByUsername($username)
  {
    $sth = $this->Db->prepare("SELECT * FROM users WHERE username LIKE :username");
    $sth->bindValue(":username", $username);
    $sth->execute();
    return $sth->fetch(PDO::FETCH_ASSOC);
  }
}

This is the db_connect.php

<?php
$host='localhost';
$user='*******';
$password='******';
$dbase='finance_app';

try {
  $db = new PDO('mysql:host=localhost; dbname=finance_app', $user, $password);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
  echo $ex->getMessage();
}
include_once'CRUD.php';
$crud = new CRUD($db);
?>

Upvotes: 0

Views: 34

Answers (1)

I believe the constructor should have double '_'. So in this case your constructor as defined might not be executing.

<?php
class CRUD
{
  private $Db;
  function __construct($DB_CON)
      $this->Db = $DB_CON;
  }

Upvotes: 3

Related Questions