未定义的索引:PHP 复选框



这个想法是有复选框列表供用户选择流派类型。流派输入来自数据库。因为 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
}
?>

您需要为复选框命名,并且由于您允许多个选择(复选框与单选按钮(,因此您需要使用 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']

最新更新