未定义的索引:PHP复选框

时间:2018-10-21 00:43:15

标签: php html css

想法是让复选框列表供用户选择流派类型。类型输入来自数据库。因为sql将结果返回到数组中,所以for循环将获取所有值并将其放入复选框。错误来自循环中的第三行。显示未定义的索引类型

<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
}
?>

1 个答案:

答案 0 :(得分:3)

您需要为复选框指定一个名称,并且由于允许多个选择(复选框与单选按钮),因此需要使用PHP数组样式名称-

<label>
<input 
name="mycheckbox[]" 
type="checkbox" 
class="common_selector genre" 
value="<?php echo $row['genre'];?>"
<?php // here is where you could throw a check to make it pre-selected
by printing the word "checked" if a logical condition is met, etc ?>
> 
<?php echo $row['genre'];?> 
</label>

现在,您可以在处理脚本中引用$_POST['mycheckbox'],它将包含一个数组,其中包含一个或多个值,每个选定值一个元素。

for($i=0;$i<count($_POST['mycheckbox']);$i++){
  print("selected value $i: ".$_POST[['mycheckbox'][$i]."\n");
}

编辑-

只是为了咯咯地笑,如果您只想要一个选择(单选按钮),仍将元素命名为相同的东西,则只需省略PHP数组括号[]

<label>
<input 
name="myradio" 
type="radio" 
class="common_selector genre" 
value="<?php echo $row['genre'];?>"
<?php /* here is where you could throw a 
      check to make it pre-selected
      by printing the word "selected" 
      if a logical condition is met, etc 
      note in a series the last one selected
      stays selected if you print selected more than once
      */
?>
> 
<?php echo $row['genre'];?> 
</label>

并且所选的无线电组值可作为$_POST['myradio']

使用