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.)

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?