0

trying to follow a OOP PDO tutorial which is a guide for creating a DB class.

I am getting the following error however when trying to use this class.

Fatal error: Call to a member function prepare() on a non-object

The line it points to is this function:

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

The class before that is:

class Database {
private $host      = 'localhost:8889';
private $user      = 'root';
private $pass      = 'root';
private $dbname    = 'PHPGamble';

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
    );
    // Create a new PDO instanace
    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);
    }

I am trying to use the class like this:

  require('../libs/PHP_Classes/class.database.php');
  $database = new Database();

  // insert new table
  $database->query('INSERT INTO tables (table_buyin) VALUES (:table_buyin)');
  $database->bind(':table_buyin', '50');
  $database->execute();

Any help on where this is going wrong?

Thanks.

Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • 2
    Where you have this line: `$this->error = $e->getMessage();` - what happens if you add `var_dump($this->error);` immediately afterwards (inside the `catch() { }` block)? Looks like you might not actually getting connected properly... – random_user_name Sep 18 '14 at 23:14
  • Bingo, was thinking I would see an error if it wasn't connecting properly by default. This is the issue, many thanks! – Lovelock Sep 18 '14 at 23:16

0 Answers0