我刚刚开始使用 PDO,并在几个教程中查找了答案,但我无法使其正常工作。

我有

Notice: Undefined property: PDOStatement::$fetch in E:\-------- on line 22
Result: 1


$dsn = "mysql:host=localhost;dbname=the_database;";
try {
    $dbh = new PDO($dsn, "root", "");
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e){
    die( "failed conexion: ".$e->getMessage() );
}


$query = "SELECT MAX(price) AS max, MIN(price) AS min FROM cellphones";
try {
    $sth = $dbh->prepare($query);
    $sth->execute();
    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $result = $sth->fetchAll;
    }
catch(PDOException $e){
    echo $e->getMessage();
    }
die( "<br />Result: ".print_r($result, true) );

我得到相同的结果
$sth = $dbh->query($query);
$result = $sth->fetchAll;


$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetch;

我得到的是它可能会返回结果计数
但为什么?以及为什么它给了我一个关于 fetch/fetchAll 甚至没有声明的通知。
我也没有任何异常(exception)。

最佳答案

您需要使用带括号的方法调用:

$sth->fetchAll();
或者 $sth->fetch();
不仅仅是
$sth->fetchAll;
PHP 认为您试图访问名为 fetchAll 的属性!

关于php - 未定义的 fetchAll 并在返回的 PDOStatement 中获取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13144855/

10-11 01:35