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

使用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";
    }
}

图片转代码服务由CSDN问答提供 功能建议

我使用PDO向我的网站添加搜索输入和按钮,我的其他声明有效,我收到'没有结果 ”。 然而我的while声明似乎没有回应。 我错过了什么,或者我在代码中写错了什么?

  if(isset($ _ POST ['submit'])){
 $ search = $ _POST [  'search']; 
 $ articles = $ db-&gt; prepare(“SELECT * FROM articles WHERE headline =:search”); 
 $ articles-&gt; execute(array(':search'=&gt; $ search)  )); 
 
 if($ articles  - &gt; rowCount()&gt; 0){
 while($ rows = $ articles-&gt; fetchAll(PDO :: FETCH_ASSOC)){
 $ headline = $ rows  ['headline']; 
 echo“标题:$ headline&lt; br&gt;”; 
} 
}其他{
 echo“无结果”; 
} 
} 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    点赞 打赏 评论

相关推荐 更多相似问题