以一种形式将不同的复选框名称从HTML发送到PHP


Send different checkbox names from HTML to PHP in one form

我对html和php比较陌生。我尝试在php中使用以html形式选择的值。

我发现了很多例子,当只有一个像vehicle[]这样的form name时,如何在php中读取html form
但我想区分input(车辆或住宿)的类型,并且仍然只有一个submit button。我试过下面的例子,但它不起作用。。。

test.html的html片段:

<form action="form.php" method="POST">
  <input type="checkbox" name="vehicle[]" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle[]" value="Car" checked> I have a car<br>
  <input type="checkbox" name="accomodation[]" value="House"> I have a house<br>
  <input type="checkbox" name="accomodation[]" value="Yurt"> I have a yurt<br>
  <input type="submit" value="Submit">
</form>

来自form.php的php片段:

<?php
  if(isset($_POST['submit']))
  {
    if(!empty($_POST['vehicle'])) 
    {
      foreach($_POST['vehicle'] as $vehiclecheck)
      {
        echo $vehiclecheck;
        echo "<br>";
      } 
    }
    if(!empty($_POST['accomodation'])) 
    {
      foreach($_POST['accomodation'] as $accomodationcheck)
      {
        echo $accomodationcheck;
        echo "<br>";
      } 
    }
  }
?>

有没有一种简单的方法可以得到我想要的?还是我需要一个变通办法?

谢谢!

 <input type="submit" value="Submit" name="submit">  //name attribute missing here

试试这个。为了简单起见,它只是一个form.php的文件

<?php
if (!empty($_POST)) {
    if(!empty($_POST['vehicle'])) {
        foreach($_POST['vehicle'] as $vehiclecheck) {
            var_dump($vehiclecheck);
        } 
    }
    if (!empty($_POST['accomodation'])) {
        foreach($_POST['accomodation'] as $accomodationcheck) {
            var_dump($accomodationcheck);
        }
    }
}
?>
<form action="form.php" method="POST">
    <input type="checkbox" name="vehicle[]" value="Bike"> I have a bike<br>
    <input type="checkbox" name="vehicle[]" value="Car" checked> I have a car<br>
    <input type="checkbox" name="accomodation[]" value="House"> I have a house<br>
    <input type="checkbox" name="accomodation[]" value="Yurt"> I have a yurt<br>
    <input type="submit" value="Submit">
</form>

注意事项:

1.)尝试以下编码风格指南,对于PHP,它是PSR-2http://www.php-fig.org/psr/psr-2/.

2.)在您的示例中,您试图检查名为"submit"的post字段是否为空。事实上,这个字段不存在,并且总是空的)

3.)与echo相比,使用var_dump是简化调试的更好方法,因为它可以更好地设置,显示变量类型,不需要显式地写新行等。

4.)关于如何在PHP中变得更好,还有一个很好的来源,请尝试一下http://www.phptherightway.com/