Implementation of DatabaseTable Class from PHP & MySQL: Novice to Ninja, 6th Edition not working

Following guidance from the mentioned book, I’ve made a version of the DatabaseTable class from chapter 8. When I go to use it however the PDO instance that is saved in the object disappears when I use one of it’s functions.

I get an error “Fatal error : Uncaught Error: Call to a member function prepare() on null in…” which means the variable that is supposed to be set to an instance of the PDO is null.
when I check its value of $this->dbc in the constructor it is a PDO but in the function $this->dbc is null.

Here’s the beginning of the class with constructor:


<?php
class DatabaseTable
{
  private $dbc;
  private $table;
  private $primaryKey;

  public function __construct(PDO $dbc, $table, $primaryKey)
  {
    $this->dbc = $dbc;
    $this->table = $table;
    $this->primaryKey = $primaryKey;
  }

and here’s the function I’m calling in the class:


  public function universalFind($columnValuePairs)
  {
    if ($this->$dbc instanceof PDO){echo '<h2>There is a PDO set</h2>';};
    $query = 'SELECT * FROM `' . $this->table . '` WHERE';
    $params = [];
    foreach ($columnValuePairs as $column => $value)
    {
      $query .= ' `' . $column . '` = :' . $column . ' AND';
      $params[$column] = $value;
    }
    $query = rtrim($query, 'AND');
      echo '<h2>' . $this->table . '</h2>';
      if ($this->$dbc instanceof PDO){echo '<h2>There is a PDO set</h2>';}else{echo '<h2>WTF happened to my PDO!!!</h2>';};
    $query = $this->query($query, $params);
    return $query->fetchAll();
  }

Any help in diagnosing this problem would be greatly appreciated as I cannot find any help after hours of searching with any parameters that I can think of. In fact hours of searching online and I’ve not come across a single case of an example of this implementation outside of this book.

Thank you.

The most immediate problem is, that’s not the correct syntax to access a property. You don’t use a $ in front of dbc.

Next, the error is (probably) occurring in the query() method. Since you didn’t post the code for that, you could have a typo in a variable name, or some other problem, maybe even an extra $ in it too.

1 Like

And there you have it folks! Thanks a bunch!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.