rhill45
rhill45

Reputation: 569

While loop only delivering first sql row

Source code is showing 16 items as requested by LIMIT. However all are only the first item in the column 'category'. How can i get this to show the first 16 rows of the column, not just the first one.

<div id="contentContainer" class="trans3d">
  <?php include("../scripts/db.php");
    $query="SELECT category FROM stories LIMIT 16"; 
    $result=mysqli_query($connection,$query);
  ?>
     <section id="carouselContainer" class="trans3d">
  <?php   
      while($data=mysqli_fetch_assoc($result)):
            $genre=$data['category'];
            $genre_path=$genre.".php"; 
            $genre_img_path="../images/genre_images/".$genre.".jpg";
  ?>

<a href="$genre_path">
    <figure class="carouselItem trans3d">
        <?php echo $genre;?>
            <img src="<?php echo $genre_img_path;?>" alt=""/>
    </figure>
</a>
<?php 
     endwhile;
     mysqli_close($connection);
 ?>
        </section>

</div>

Upvotes: 0

Views: 114

Answers (2)

calbo
calbo

Reputation: 21

If you expect to get 16 different categories (with no duplicate), you should use the keyword DISTINCT

SELECT DISTINCT category FROM stories LIMIT 16

If you want the category from the 16 first lines in the table stories (possibly with duplicates), then your request is correct.

If the issue is that you do not get the category you're expecting, maybe try to ensure the correct ordering of the firstly selected rows with an ORDER BY clause.

Upvotes: 1

Barmar
Barmar

Reputation: 780714

change the query to:

$query = "SELECT DISTINCT category FROM stories LIMIT 16";

This will ensure that you get 16 different categories. Otherwise, the selection of which 16 rows is arbitrary, and it might pick 16 stories that happen to be in the same category.

Upvotes: 2

Related Questions