【问题标题】:PDO and php - Call to a member function prepare() on a non-objectPDO 和 php - 在非对象上调用成员函数 prepare()
【发布时间】:2013-08-04 18:31:48
【问题描述】:

我开始学习 PDO,但我还是个 PHP 新手。我正在做一个项目来增加我的知识,但我遇到了第一个障碍。

我收到此错误:在此代码的第 37 行调用非对象上的成员函数 prepare()。这是来自 database.class.php

<?php
// Include database class
include 'config.php';

class Database{
private $host      = DB_HOST;
private $user      = DB_USER;
private $pass      = DB_PASS;
private $dbname    = DB_NAME;

private $dbh;
private $error;

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();
    }
}

// this variable holds the temporary statement
private $stmt;

// prepare our values to avoid SQL injection
public function query($query){
    $this->stmt = $this->dbh->prepare($query);
}

// use switch to select the appropiate type for the value been passed
// $param = placeholder name e.g username, $value = myusername
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;
        }
    }
// run the binding process
$this->stmt->bindValue($param, $value, $type);
}

// execute the prepared statement
public function execute(){
    return $this->stmt->execute();
}

// returns an array of the results, first we execute and then fetch the results
public function resultset(){
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

// same as resultset() except this returns a single result
public function result_single(){
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

// count the number of rows from the previous delete, update or insert statement
public function rowCount(){
    return $this->stmt->rowCount();
}

// last insert id return the last id of the insert made, useful if you need to run a further
// query on the row you just inserted and need the id as the reference
public function lastInsertId(){
    return $this->dbh->lastInsertId();
}

// transactions allow you to rollback if a set of queries fail but it also allows ensures
// we avoid errors due to users interaction while half of the queries are still being written

// the following code begins a transaction
public function beginTransaction(){
    return $this->dbh->beginTransaction();
}

// end a transaction
public function endTransaction(){
    return $this->dbh->commit();
}

// rollback a transaction
public function cancelTransaction(){
    return $this->dbh->rollBack();
}

// this dumps the PDO information from the prepared statement for debug purposes
public function debugDumpParams(){
    return $this->stmt->debugDumpParams();
}

}

?>

现在,我在 index.php 中运行此代码的初始页面

<?php

// Include database connection class
include 'includes/database.class.php';
include 'includes/bug.class.php';

$database = new Database;
$bugs = new Bugs;
$bugs->find_all_rows();

echo "<pre>";
print_r($rows);
echo "</pre>";

echo "Number of rows: " . $bugs->rowCount() . "<br />";


?>

这是运行 find_all_rows 函数的页面,其中有 bugs.class.php 文件

<?php
class Bugs {

    public function find_all_rows() {
      return self::find_by_sql('SELECT * FROM tbl_priority');   
    }

    public function find_by_sql($sql="") {
      global $database;
      $database->query($sql);
      $rows = $database->resultset();

      return $rows;
    }
}
?>

是否有调试工具可以帮助我更好地跟踪这些类型的错误,或者这只是我对 PDO 不够熟悉而无法发现明显错误的情况?

【问题讨论】:

  • $this-&gt;error 的值是多少?你为什么不给 class Bugs 它是非常自己的数据库对象,以便你确定它被实例化了? (这是 OOP 的“法则”之一)
  • 它是一个服务器错误,所以它甚至没有加载索引页面,我刚开始学习 Pdo,所以我确定上面可能有很大的错误,我只是在寻找一个正确的方向,一旦我得到几个查询工作我认为我无法从那里弄清楚大部分情况
  • 当你说给类错误它自己的数据库对象时,你的意思是类错误扩展数据库吗?
  • 不幸的是,这不是一个代码审查网站,可以提防上述所有重大错误。您必须逐步编写代码,而不是一次完成。分别调试各个部分。
  • 你得到的错误说$this-&gt;dbh不是一个对象,这很可能意味着$this-&gt;dbh = new PDO($dsn, $this-&gt;user, $this-&gt;pass, $options);失败了。由于您正在处理该异常,因此您不会立即看到这一点。

标签: php mysql pdo


【解决方案1】:

@papaja 一针见血。您的 PDO 连接失败,因此您没有要在其上运行准备方法的 PDO 对象。

在我的脑海中,我认为您缺少 $dsn 字符串的结尾引号。您可能希望在 $this->dbname 之后和分号之前添加以下内容:

. "'"

这是用双引号包裹的单引号。我使用以下语法来创建 DSN 字符串:

"mysql:host=$this->HOST;dbname=$this->DATABASE"

无论如何,创建一个测试文件,以便您确切知道问题所在。测试文件应如下所示:

class TestDatabase{

    private $host      = DB_HOST;
    private $user      = DB_USER;
    private $pass      = DB_PASS;
    private $dbname    = DB_NAME;
    private $dbh;


    public function __construct(){

        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;

        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );

        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
}

请注意,我们没有在 try catch 块中运行 PDO 对象的实例化。虽然您永远不会在生产环境中这样做,但它对您的测试很有用,因为它会抛出一个包含所有连接细节的致命异常。

现在实例化测试类并继续调试收到的错误。同样,它们将比以前的错误更详细,因为它将是未捕获的 PDO 异常。

【讨论】:

  • 谢谢,原来是连接,现在工作正常
【解决方案2】:

遇到同样的错误,无法用上面编写的代码修复。

这里很容易修复,因为在您的代码中这就是 PDO 发送错误的问题:

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();
    }
}

我使用的是 PHP 5.5,如果有人有同样的错误,那么他将需要这个

在 $dns 之后,您需要在 $this->dbname 处添加它。 ";";

只有这样它才能在 PHP 5.5 中工作,并且不适用于 $this->dbname 。 "'";

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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2014-09-04
    • 2013-08-21
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多