jeudi 17 décembre 2015

Send different checkbox names from HTML to PHP in one form

I'm relatively new to html and php. I'm trying to use values chosen in an html form in php.

I've found lots of examples, how to read out the html form values in php when there is only one form name like "vehicle[]".
But I would like to differenciate between types of input (vehicle or accomodation) and still have only one submit button. I've tried the following example, but it doesn't work ...

The html snippet from test.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>

The php snippet from form.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>";
      } 
    }

  }
?>

Is there a simple way to get what I want? Or do I need a workaround?

Thanks!




Aucun commentaire:

Enregistrer un commentaire