PDO致命错误:在...文件中的非对象上调用成员函数fetch()

时间:2013-04-09 19:44:44

标签: php pdo

我知道这已被问过好几次,但我找不到符合我情况的那个,所以,不得不问。

我有两个文件
1)connection.php

class Database {

    protected $dbh;

    public function __construct() {
        $dsn = 'mysql:dbname=dbname;host=localhost';
        $user = 'dbuser';
        $pass = 'dbpass';

        try {
            $this->dbh = new PDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
    }

    public function displayInfo() {
        $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
        return $stmt->execute();
    }

}

$db = new Database();

2。)info.php

require_once 'connection.php';

$result = $db->displayInfo();

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo $row['fname']. " " . $row['lname'];
}

我知道我无法将fetch()$result一起使用,如果它在同一页面中我可以使用$stmt->fetch(),但无法弄清楚如何调用此PDO fetch来自另一页。

2 个答案:

答案 0 :(得分:1)

PDOStatement::execute()方法成功时返回true,失败时返回false - 不是查询结果。您需要返回您的陈述:

public function displayInfo() {
    $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
    $stmt->execute();
    return $stmt;
}

通过这种方式,$result变量实际上是您的语句,您可以在其上调用fetch()方法。

更好的方法是从displayInfo()方法内部进行提取并返回结果,而不必依赖于将数据库好东西带到类之外:

class Database 
{

   protected $dbh;

   public function __construct() {
      $dsn = 'mysql:dbname=dbname;host=localhost';
      $user = 'dbuser';
      $pass = 'dbpass';

      try {
         $this->dbh = new PDO($dsn, $user, $password);
      } catch (PDOException $e) {
         echo 'Connection failed: ' . $e->getMessage();
      }
   }

   public function getDisplayInfo() {
      $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
      if( $stmt->execute() ) {
         return $stmt->fetch(PDO::FETCH_ASSOC);
      }
      // Query failed
      return false;
   }
}

$db = new Database();

$results = $db->getDisplayInfo();

foreach($results as $row) {
   echo $row['fname']. " " . $row['lname'];
}

答案 1 :(得分:-1)

正确的代码。请参阅PDO tag wiki

中的详细信息
class Database {

    protected $dbh;

    public function __construct() {
        $dsn = 'mysql:dbname=dbname;host=localhost';
        $user = 'dbuser';
        $pass = 'dbpass';
        $opt = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
        $this->dbh = new PDO($dsn, $user, $password, $opt);
    }

    public function displayInfo() {
        $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
        $stmt->execute();
        return $stmt->fetchAll();
    }

}