0

I'm attempting to create a somewhat simple database abstraction layer. All seemed to be going well until I tried to test it with a query which it will not work with. Looking for a little help on this one.

Errors:

( ! ) Notice: Undefined variable: dbh in C:\wamp64\www\phpwebsite\db.php on line 29

( ! ) Fatal error: Call to a member function query() on null in C:\wamp64\www\phpwebsite\db.php on line 29

DB Class:

include_once 'IAbstractDatabase.php';

class db implements IAbstractDatabase
{
public function __construct()
{
    $username = "root";
    $pass = "";

    try {   
        $dbh = new PDO("mysql:host=localhost;dbname=imperialcars", $username, $pass);
    } catch (PDOException $e) {
        echo $e->getMessage()."</br>";
        die();
    }
}
public function __destruct()
{
    $dbh=null;
}
public function select($query)
{
    return $stmt = $dbh->query($query);
}
public function query($query)
{
    return $stmt = $dbh->query($query);
}
}

$dbh = new db();
$dbh->query("INSERT INTO users (userid, username, userfname, userlname, email, password, banned, admin) VALUES (NULL, 'user2', 'john', 'doe', 'johndoe@hotmail.com', 'password', '0', '0')");

Appreciate your help and feedback.

user5561715
  • 23
  • 1
  • 9
  • Related: [Your first database wrapper's childhood diseases](https://phpdelusions.net/pdo/common_mistakes) – Your Common Sense Jan 19 '17 at 13:25
  • Your issue is actually with scoping variables within the object... none of your methods can access `$dbh` as it's not a class member : http://php.net/manual/en/language.oop5.properties.php – CD001 Jan 19 '17 at 13:45
  • @CD001 Thank you for your reply. Could you tell me how you would go about solving this issue? I've declared the $dbh as private at the start of the class. Now I'm getting just the second error.. – user5561715 Jan 19 '17 at 13:54
  • You methods would need to call that private `$dbh` class member with `$this` ... so `$this->dbh->query( ... );` – CD001 Jan 19 '17 at 14:35

0 Answers0