trying to learn the ins and outs of PDO and I just got into this brick wall.
My current PDO class is the following:
class SimpleDatabase extends PDO {
const DB_HOST='localhost';
const DB_USER='claudio';
const DB_PASS='claudio';
const DB_NAME='simpledb';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . self::DB_HOST . ';dbname=' . self::DB_NAME;
// 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, self::DB_USER, self::DB_PASS, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function __destruct(){
// Adding null connection
$this->dbh = null;
$this->isConnected = false;
}
// The query, prepare, bind and execute methods allows us to use prepared statements in our DB interactions
// Prepare
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
// Bind
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
// Execute
public function execute(){
return $this->stmt->execute();
}
I do have the rest of the functions but for this error in particular I don't think it's necessary to show you the rest.
Then I'm calling the function this way:
$database = new SimpleDatabase();
$database->query('INSERT INTO mytable (FName, LName, Age, Gender) VALUES (:fname, :lname, :age, :gender)');
$database->bind(':fname', 'John');
$database->bind(':lname', 'Smith');
$database->bind(':age', '24');
$database->bind(':gender', 'male');
$database->execute();
And I'm getting the following error: Fatal error: Call to a member function prepare() on null, and this happens when I call the prepare function. Any idea on why this is happening and how can I solve this problem?
bind()function?destructorie__destuct()__destruct();-)__destuct(), am I missing something?