PHP : checkboxes and name issue
I'm writing, for the first time in PHP, a script to process a POSTed form that contains checkboxes.
As you know, checkboxes are grouped by using the same name attribute, and when multiple values occur, $_POST["some_name"] should be storing those in an array.
I tested but instead of the expected array I got one single value -- that of the last checked item.
At this point, somewhat puzzled, I look at some doc to开发者_Python百科 discover that with PHP the checkbox name should end with []
. Is that so? What crazy relation is there expected to exist between an HTML form and a script that processes it? Suppose I don't have access to the HTML field names? Suppose, as it is my case, I have every good reason not to alter my naming scheme just for some obscure nonsense.
Now, it seems there exists at least one solution to the issue: PHP: Retrieving value of checkboxes when name doesn't have array
I'd like to know if there's a really simple way to do without those crazy brackets, and, incidentally, your opinion on this point? Am I the only one shocked?
EDIT : OK, I can certainly work my way around this issue, but I hoped to be raising some (minor yet) fundamental point regarding some sort of "non-separation of concerns" between HTML and PHP. Obviously, that's none of PHP's business how HTML code should be written.
In your html code for the checkboxes:
name="mycheckboxname[]"
You should try with
<input type="checkbox" name="mycheckbox[]" value="Male" />
<input type="checkbox" name="mycheckbox[]" value="Female" />
In php side,
$myCheckBoxCollection = $_REQUEST['mycheckbox'];
What is your good reason for not incorporating [] in your naming scheme ? I don't think this is particularly shocking. As far as PHP is concerned, maybe you actually were expecting to only get the value from the last element with that particular name.
There are some alternatives such as the one you included in your question, or fetching the values with some javascript trickery, but I don't think you will find any that's easier than simply adding brackets to the name of your checkboxes.
精彩评论