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

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

php - Get POST data from multiple checkboxes?

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

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

1 Answer

0 votes
by (71.8m points)

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>";
     }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...