用于打印复选框项目的PHP循环

时间:2014-06-20 14:38:45

标签: php checkbox

您好我正在尝试制作一个表单,其中所选文本框在同一页面上打印为div。

如果我点击两个方框,它只返回最后一个项目。有谁知道我应该如何修改我的以下PHP,以便它将所有检查的项目通过?

 if (empty($aBox)) 
  {
    $error = "You must enter something.";  
  } 

  else
  {
    $N = count($aBox);

    for($i=0; $i < $N; $i++)

    {
       $passit = ($aBox[$i] . " ");
    }
  }


  if (isset($error)) {  
    header("Location: galarieproject.php?e=".urlencode($error)); exit;  
  }  

  header("Location: galarieproject.php?s=".urlencode("You selected:" . " ").$passit); exit;  

这是我的HTML表单:

<?php  

        // check for a successful form post  
        if (isset($_GET['s'])) echo "<div class=\"alert alert-success\">".$_GET['s']."</div>";  

        elseif (isset($_GET['e'])) echo "<div class=\"alert alert-error\">".$_GET['e']."</div>";  

        // check for a form error  
    ?>


    <div class="table-responsive">
      <form action="checkbox-form.php" method="POST">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Importance</th>
                  <th>Item</th>
                  <th>New/Used?</th>
                  <th>Donate:</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1</td>
                  <td>Cork Board</td>
                  <td>Either</td>
                  <td><input type="checkbox" name="checkOne[]" value="Corkboard"></td>
                </tr>
                <tr>
                  <td>2</td>
                  <td>Barndoor Lights</td>
                  <td>Either</td>
                  <td><input type="checkbox" name="checkOne[]" value="Barndoor"></td>
                </tr>
                <tr>
                  <td>3</td>
                  <td>Lighting Stands</td>
                  <td>Either</td>
                  <td><input type="checkbox" name="checkOne[]" value="Lightstand"></td>
                </tr>
              </tbody>
            </table>

            <input type="submit" name="formSubmit" value="Submit" />
        </form>

1 个答案:

答案 0 :(得分:1)

你没有添加多个项目以便你覆盖它们,在这里foreach会比for循环更好。

if (empty($checkOne)) {
    $error = "You must enter something.";  
} else {
    foreach($checkOne as $box) {
       $passit .= $box . " ";
    }
}


if (isset($error)) {  
    header("Location: galarieproject.php?e=".urlencode($error)); 
    exit;  
}  

header("Location: galarieproject.php?s=".urlencode("You selected:" . " ").$passit); 
exit;