2015-02-23 83 views
0

试图学习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(); 

而且我发现了以下错误:致命错误:调用一个成员函数上的空准备(),并且这种情况发生时,我打电话准备功能。任何想法为什么发生这种情况,我该如何解决这个问题?

+0

你的'bind()'函数在哪里? – 2015-02-23 22:11:46

+0

已编辑为具有绑定和执行功能。 – 2015-02-23 22:14:07

+0

就这样,你知道你拼错了'析构函数'即'__destuct()' – Cyclonecode 2015-02-23 22:16:18

回答

1

它看起来像你的代码是“吞服”尝试数据库连接时引发的PDO异常,并失败。

这里:

catch(PDOException $e){ 
     $this->error = $e->getMessage(); 
    } 

如果有异常升高时,你分配的东西给error成员。凉。但如果连接失败,可能$this->dbh将会为空。

但是,否则它看起来好像你的代码只是继续,就好像一切都很好。

就好像你的代码正在把它的小指放在它的嘴角,Dr.Evil风格,并说:“我只是假设一切都会按计划进行,什么?

+0

你说得对,我只是抛弃了错误,很容易理解这个问题。非常感谢,我只是错过了。 – 2015-02-23 22:29:18

相关问题