试图学习PDO的来龙去脉,我刚进入这个砖墙。PHP PDO致命错误:调用成员函数prepare()null
我现在的PDO类如下:
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();
}
我有职能的休息,但这个错误特别是,我不认为有必要向您展示的休息。
然后我打电话的功能是这样的:
$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();
而且我发现了以下错误:致命错误:调用一个成员函数上的空准备(),并且这种情况发生时,我打电话准备功能。任何想法为什么发生这种情况,我该如何解决这个问题?
你的'bind()'函数在哪里? – 2015-02-23 22:11:46
已编辑为具有绑定和执行功能。 – 2015-02-23 22:14:07
就这样,你知道你拼错了'析构函数'即'__destuct()' – Cyclonecode 2015-02-23 22:16:18