Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Im trying to create a form using PHP and I cant seem to find a tutorial on what I need so thought Id ask on here.

I have a multiple checkbox option on my page...

 <li>
    <label>What service are you enquiring about?</label>
    <input type="checkbox" value="Static guarding" name="service">Static guarding<br>
    <input type="checkbox" value="Mobile Patrols" name="service">Mobile Patrols<br>
    <input type="checkbox" value="Alarm response escorting" name="service">Alarm response escorting<br>
    <input type="checkbox" value="Alarm response/ Keyholding" name="service">Alarm response/ Keyholding<br>
    <input type="checkbox" value="Other" name="service">Other<input type="hidden" value="Other" name="service"></span>
  </li>

I'm not sure however how to collect all checkbox values using POST method?

if i use

$service = $_POST['service'];

I only get 'other' returned

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

Name the fields like service[] instead of service, then you'll be able to access it as array. After that, you can apply regular functions to arrays:

  • Check if a certain value was selected:

     if (in_array("Other", $_POST['service'])) { /* Other was selected */}
    
  • Get a single newline-separated string with all selected options:

     echo implode("
    ", $_POST['service']);
    
  • Loop through all selected checkboxes:

     foreach ($_POST['service'] as $service) {
         echo "You selected: $service <br>";
     }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...