【问题标题】:PHP PDO fetchAll() on bool布尔上的 PHP PDO fetchAll()
【发布时间】:2019-08-07 17:46:23
【问题描述】:

我尝试编写自己的 PDO 包装类,我的语句总是返回 true,但我无法获取任何内容。

这是我的DB 课程

class DB {

private $db;
private $host = "localhost";
private $database = "test";
private $user = "test";
private $password ="test";

public function __construct(){
    try {
        $this->db = new \PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->user, $this->password);
        $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    } catch (\PDOException $error) {
        die("Verbindung zur Datenbank fehlgeschlagen: <br>" . $error);
    }
}

public function run($sql, $args = []){
    try{
        $stmt = $this->db->prepare($sql);
        $result = $stmt->execute($args);
        return $result;
    } catch(\PDOException $error) {
        die("Fehler bei Datenbankabfrage: <br>". $error);
    }
}
}

在这里我实例化了我的类的一个新实例并尝试获取数据

$DB = new DB();
$data = $DB->run("SELECT * FROM testtbl")->fetchAll();

如果没有 fetchAll(),它会返回 true,并且会在我的 error.log 中引发错误

PHP 致命错误:未捕获的错误:在布尔值上调用成员函数 fetchAll()

如果有人可以帮助我,那就太好了。

【问题讨论】:

    标签: php mysql sql oop pdo


    【解决方案1】:

    PDOStatement::execute 只返回一个布尔值,表示查询是否成功。你需要在语句上调用fetchAll,所以而不是

    return $result;
    

    你应该有

    return $stmt;
    

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2017-09-25
      相关资源
      最近更新 更多