dozan0001 2017-08-23 13:47
浏览 74
已采纳

使用PDO和PHP搜索数据库,而语句不显示echo

I am adding a search input and button to my website using PDO, my else statement works and I receive 'no results'. However my while statement seems to have no response. Am I missing anything or have I written something wrong in my code?

if(isset($_POST['submit'])){
    $search = $_POST['search'];
    $articles = $db->prepare("SELECT * FROM articles WHERE headline = :search");
    $articles->execute(array(':search' => $search));

    if($articles -> rowCount() > 0) {
            while ($rows = $articles->fetchAll(PDO::FETCH_ASSOC)){
                   $headline = $rows['headline'];
                   echo "headline: $headline<br>";
                  }
    } else{
        echo "No Results";
    }
}
  • 写回答

1条回答 默认 最新

  • doudao5287 2017-08-23 13:53
    关注

    You used the wrong fetch method.

    while ($rows = $articles->fetchAll(PDO::FETCH_ASSOC)) { ...
    

    fetchAll fetches all the rows. So $rows is an array of rows, not one row. Consequently the loop will only execute once, and $rows['headline']; won't exist.

    Just use fetch instead of fetchAll.

    Alternatively, if you still want to use fetchAll, you can call it once and then iterate the result with a foreach loop.

    $rows = $articles->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $row) {
        $headline = $row['headline'];
        echo "headline: $headline<br>";
    }
    

    Either way should work the same.


    You should have error reporting set to display warnings and notices on your development server, so PHP can inform you of problems like this. ($rows['headline'] would generate an undefined index notice.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败