获取PHP中的选中复选框

时间:2019-04-09 14:59:08

标签: php checkbox

我无法在PHP中获得复选框的输入。 这是我的代码:

echo "<table>";

while ($zeile = mysqli_fetch_array( $ergebnis, MYSQLI_ASSOC )){
    echo "<tr>";
    echo "<td> <input type='checkbox' name='check_list[]' id='".$zeile['AGName']."'/> </td>";
    echo "<td>". $zeile['AGName'] . "</td>";
    echo "</tr>";
}

echo "</table>";

#this is the part that probably isn't correct.
if(!empty($_POST['check_list'])){
    $checked_count = count($_POST['check_list']);
    echo "You have selected following ".$checked_count." option(s): <br/>";
}

我想检查复选框的数量。 复选框是使用数据库的输入循环创建的。 即使可行,我如何获取所有选中复选框的ID?

1 个答案:

答案 0 :(得分:1)

似乎您没有使用form进行提交。将表格放在form

<form action="" method="post">
<?php
  echo "<table>";

  while ($zeile = mysqli_fetch_array( $ergebnis, MYSQLI_ASSOC )){
    echo "<tr>";
    echo "<td> <input type='checkbox' name='check_list[]' value='".$zeile['AGName']."'/> </td>";
    echo "<td>". $zeile['AGName'] . "</td>";
    echo "</tr>";
 }

 echo "</table>";

?>
</form>

您可以获得post

if($_POST){
   $checked_count = count($_POST['check_list']);
   echo "You have selected following ".$checked_count." option(s): <br/>";
 }

带有复选框的简单表格:-

<form name="" action="" method="post">
  <input type="checkbox" name="gender[]" value="Male" />Male
  <input type="checkbox" name="gender[]" value="Female" />Female
  <input type="submit" name="submit" value="Submit" />
</form>

用于获取所选内容的PHP代码:-=

if(isset($_POST['gender'])){
   $options = $_POST['gender'];
   echo implode(',', $options);
}

如果您想传递ID,可以这样做

 <input type="checkbox" name="gender[2]" value="Male" />Male
 <input type="checkbox" name="gender[3]" value="Female" />Female

您可以遍历每个选项

foreach($options as $key => $value){
   echo $key.'---'.$value;
}
//$key is the id sepcified, $values is the seected value