注意:未定义变量方法PDO::fetchAll()


PHP How to fix Notice: Undefined variable method PDO::fetchAll()

我使用PDO select时有这个问题。

$db = new PDO("mysql:host=localhost;dbname=web", "root", "");
$result = $db->prepare('SELECT id, name, place, add FROM system_tab"');
$result->execute();
$result = $db->fetchAll();
foreach( $result as $row ) {
    echo $row['first_name'];
    echo $row['last_name'];
}
$db = null;

我得到了这个错误,谢谢你的帮助。

致命错误:调用

中的未定义方法PDO::fetchAll()

请尝试下面的代码…实际上,你正在尝试调用fetchAll方法到db对象,但这个fetchAll方法应该应用于持有执行查询指针的语句。所以应该如下所示。

$db = new PDO("mysql:host=localhost;dbname=web", "root", "");
$stmt = $db->prepare('SELECT id, name, place, add FROM system_tab"');
$stmt->execute();
$result = $stmt->fetchAll();
foreach( $result as $row ) {
    echo $row['first_name'];
    echo $row['last_name'];
}

我希望这对你有帮助,欢迎评论

您需要获取$result而不是$db

Try this:

$result = $db->prepare('SELECT id, name, place, add FROM system_tab"');
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
 echo $row['first_name'];
 echo $row['last_name'];
}