致命错误:未捕获错误:在数组上调用成员函数fetch()

时间:2020-03-29 19:55:05

标签: php mysql pdo

当我执行以下代码时,输​​出很好,我得到了3条记录:

$sql = "SELECT * FROM log WHERE follow=1 AND action = 'new' AND processed = 0 AND type = 'question'";
$result = $db->prepare($sql);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)):
    echo $row['action']." ".$row['type']." id: ".$row['type_id'].'<br>';
    //insert more sql in here
endwhile;

没有错误。

在添加到while循环之前,我还有更多的sql分别测试:

    $id=$row['type_id'];
    //retrieve all new questions - name and content & compile into message
    $stmt = $db->prepare("SELECT * FROM questions WHERE question_id=?");
    $stmt->execute([$id]); 
    $result = $stmt->fetch();
    $content = $result['question'];
    $author_id = $result['user_id'];

    //get author name
    $stmt = $db->prepare("SELECT username FROM users WHERE id=?");
    $stmt->execute([$author_id]); 
    $result = $stmt->fetch();
    $name = $result['username'];
    echo '<strong>'.$name.': </strong>'.$content.'<br>';

我使用$ id进行测试并得到结果。

没有错误。

当我将此代码插入while循环中时,出现致命错误。它执行一个循环并失败。

Fatal error: Uncaught Error: Call to a member function fetch() on array

完整代码:

$sql = "SELECT * FROM log WHERE follow=1 AND action = 'new' AND processed = 0 AND type = 'question'";
$result = $db->prepare($sql);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)):
    //echo $row['action']." ".$row['type']." id: ".$row['type_id'].'<br>';
    $id=$row['type_id'];
    //retrieve all new questions - name and content & compile into message
    $stmt = $db->prepare("SELECT * FROM questions WHERE question_id=?");
    $stmt->execute([$id]); 
    $result = $stmt->fetch();
    $content = $result['question'];
    $author_id = $result['user_id'];

    //get author name
    $stmt = $db->prepare("SELECT username FROM users WHERE id=?");
    $stmt->execute([$author_id]); 
    $result = $stmt->fetch();
    $name = $result['username'];
    echo '<strong>'.$name.': </strong>'.$content.'<br>';

endwhile;

我怀疑很简单,但似乎看不到它。 预先感谢!

1 个答案:

答案 0 :(得分:0)

午餐后休息一下,这很明显-我在所有3个查询中都使用$ result。我将其更改为$ result,$ result2,$ result3,这样就解决了问题:

$sql = "SELECT * FROM log WHERE follow=1 AND action = 'new' AND processed = 0 AND type = 'question'";
$result = $db->prepare($sql);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)):
    //echo $row['action']." ".$row['type']." id: ".$row['type_id'].'<br>';
    $id=$row['type_id'];
    //retrieve all new questions - name and content & compile into message
    $stmt = $db->prepare("SELECT * FROM questions WHERE question_id=?");
    $stmt->execute([$id]); 
    $result2 = $stmt->fetch();
    $content = $result2['question'];
    $author_id = $result2['user_id'];

    //get author name
    $stmt = $db->prepare("SELECT username FROM users WHERE id=?");
    $stmt->execute([$author_id]); 
    $result3 = $stmt->fetch();
    $name = $result3['username'];
    echo '<strong>'.$name.': </strong>'.$content.'<br>';
endwhile;