dongnai8013 2019-04-16 15:42
浏览 61

如何修复PHP / SQL搜索查询只获取一行数据而不是所有相关行?

I'm working on a little project and I want to be able to search my database for all items associated with my search

My problem is that when I use my code below, I get only one result rather than an array of all results that fit my query. I have seen some solutions that suggested using fetchAll() but that doesn't seem to output anything.

What the PHP query looks like.

if(isset($_POST['search'])){

      if(preg_match("/^[a-zA-Z]+/", $_POST['sname'])){
      $search = $_POST['sname']; //name in form 

      $pdo = & dbconnect();

      $userid = $_SESSION['user_id'];

      $sql = "SELECT * FROM movie_dets Where user_id=? and Title LIKE '%" .$search."%'";
      $stmt=$pdo->prepare($sql);
      $stmt->execute([$userid]);

      if(!$stmt)
      {
         die("Database pull did not return data");
      }

      $row=$stmt->fetch();
   }
   }

Then I have a foreach loop in my html that looks like so

 <div class="row">
          <?php
          $loop = 0;
          foreach ($stmt as $row):   //loop through result set ?>

          <div class="column" >
             <div>
               <figure>
               <img src="<?php echo "/.../".$row['Cover'] ?>" alt="<?php echo $row['Title']; ?> cover" />
               <figcaption>
                 ...
                </figcaption>
               </figure>
            </div>
           </div>
           <?php
            $loop++;
                if ($loop % 4 ==0) //to display four results the wrap.
              {
                 echo "</div> <div class='row'>";

              }
            ?>
        <?php endforeach ?>
     </div>

In my database, there are two titles called frozen. This is supposed to output all rows when given the 'fr' search word. Instead, it only fetches one of them.

  • 写回答

0条回答 默认 最新

    报告相同问题?