Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

forms - getting multiple checkboxes names/id's with php

How can i get the names or id's of the multiple selected checkboxes on submit, using the PHP? Following is example form. Thanks.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
   <input type="checkbox" name="orange" id="orange">
   <input type="checkbox" name="apple" id="apple">
   <input type="checkbox" name="sky" id="sky">
   <input type="checkbox" name="sea" id="sea">
   <br>
   <br>
   <input type="submit" name="Submit" value="Submit">
</form>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Checkbox values are submitted from a form only if the checkbox is selected. What's more, it's the name attribute that counts, not the ID.

There are several ways of handling checkboxes in PHP:

  1. Give all checkboxes the same name followed by a pair of square brackets, so the entire set is treated as an array. In this case, give each checkbox a value.
  2. Give each checkbox a different name and a value.
  3. Give each checkbox a different name, but no value.

In each case, you need to check for the existence of the checkbox name in the $_POST array.

For example:

<input type="checkbox" name="color[]" id="orange" value="orange">
<input type="checkbox" name="color[]" id="apple" value="apple">

To get the values for these checkboxes:

if (isset($_POST['color'])) {
    $colors = $_POST['color'];
    // $colors is an array of selected values
}

However, if each checkbox has a different name and an explicit value like this:

<input type="checkbox" name="orange" id="orange" value="orange">
<input type="checkbox" name="apple" id="apple" value="apple">

You still need to use isset():

if (isset($_POST['orange'])) {
    // orange has been set and its value is "orange"
}

If you don't set a value, the default value is "on", but it won't be in the $_POST array unless it has been selected, so you still need to use isset().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...