Click here to Skip to main content
14,334,249 members
Rate this:
Please Sign up or sign in to vote.
See more:
A list of checkbox for user to select genre type. The genre input is from database. Because the sql will return the result in an array, a for loop to get all the values and make them into a check box. The error come from third line in the loop. It show undefined index genre

What I have tried:

<div class="list-group">
      <h3>Genre</h3>
      <?php
      $search_genre = "SELECT DISTINCT(genre) FROM movie_db WHERE product_status ='1' ORDER BY movieid DESC"
      $statement = mysqli_query($conn,$search_genre);
      $result = mysqli_fetch_all($statement);
      foreach ($result as $row){
         ?>
         <div class="list-group-item checkbox">
         <label><input type="checkbox" class="common_selector genre" value="<?php echo$row['genre'];?> > <?php echo $row['genre'];?></label>
</div>
<?php
}
?>
Posted
Updated 23-Oct-18 3:38am
Rate this:
Please Sign up or sign in to vote.

Solution 1

Things for you to do:

Fix code - spaces are important:
value="<?php echo$row['genre'];?> >
value="<?php echo $row['genre']; ?>"
But really, loops that build HTML should, in general, build the HTML and not just the values (from the php). Your foreach() statement should not end the php abruptly but instead build the entire HTML, like this:
 foreach ($result as $row) {
  ECHO "<div class="list-group-item checkbox">"
     . " <label><input type='checkbox' class='common_selector genre'"
     . " value=\"{$row['genre']}\"> {$row['genre']} </label>"
     . "</div>";
}

This is much more readable and puts out your rows of data. This
   
v3
Rate this:
Please Sign up or sign in to vote.

Solution 2

SELECT DISTINCT(genre) FROM movie_db WHERE product_status = '1' ORDER BY movieid DESC

That will produce a resultset with a single un-named column. As a result, your rows do not contain a column called genre.

Give your column an alias:
SELECT DISTINCT(genre) As genre FROM movie_db WHERE product_status = '1' ORDER BY movieid DESC
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100