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 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.
Related
I recently saw a html page, that i thought the id of several html tags was the same, then I realized the ids are unique but it raises the question that what could have happened if the page actually used several tags
As i have heard id attribute of every html tag(if it has one) must be unique,
now i wonder what happens if it is not the case??
what possible errors can it cause?
does different browsers show different reactions for this issue?
does javascript and jquery codes that use duplicated ids run on both tags or what?
Duplicate ids can have various different effects. Which you experience will depend on the method you use to try to access them (and possibly also from browser to browser).
You'll affect all of them
You'll affect the first one
You'll affect the last one
You'll get a collection instead of an element, try to treat it like an element and get an error
Duplicate ids are not allowed in HTML. Don't make trouble for yourself. Use classes for groups and ids for unique identifiers.
Change them as soon as possible, to save a lot of headache in the future. For elements with same property use classes
About your queries,
Now i wonder what happens if it is not the case??
Well, the HTML is not a valid one anymore. Now a days it doesn't hurt much but still not preferred.
What possible errors can it cause?
Errors are little bit hard to predict. But with jQuery you are going to get many.
Does different browsers show different reactions for this issue?
Not sure.
Does javascript and jquery codes that use duplicated ids run on both tags or what?
jQuery will give you trouble. Consider a case where you have two input fields with same ID.
and you try to select second one with out noticing. jQuery('yourID').val() and you'll be selecting the firs value instead. Like this there are a lot of possibilities.
As you said, HTML id, per specs, must be unique. If one where to put duplicated id, the js behavior relative to those ids will be unpredicatable, and could even change between 2 calls.
Any js call on one id (jquery or not) will point to one of the id but without guarentee that :
It will be the same every call
It will have the same order between 2 page refresh
It will have the same behavior beween 2 different browser
It will have the same behavior betwween 2 time the same browser
The problems that could emerge depend on how toghtly the js code is coupled to the underlying element DOM structure anw could mostly point to a undefined exception and stop the js execution.
I am doing programming in PHP and HTML these days. But the problem I am facing is that many times the data is accepted by the PHP engine using NAME attribute used in the HTML syntax of Forms but many times (like when there was a multi-radio button program) ID and NAME together gave me the required output.
Can anyone here give me a nice explanation of the concept and the difference between these two? I already tried googling but I could not understand.
Help will be appreciated :)
The name attribute is used on form controls (like <input>) to associate a known label with a (possibly) variable value that will appear in the submitted data. It does not have to be unique, but PHP will only handle multiple fields which share a name properly if that name ends in [].
<input name="foo" value="bar"> will be available through $_POST['foo'] or $_GET['foo'] when the form is submitted.
The id attribute can be used on any HTML element so it can be referenced with client side technologies (such as <label for>, JavaScript and fragment identifiers in URIs). It does have to be unique.
NB: It is possible to use a name attribute to reference an element with client side technologies, but it is almost always a better idea to use id (or class for groups of elements) rather then adding a name attribute.
Is there anything bad in using post arrays for post variables?
<input type="text" id="stuff" name="stuff[text]"/>
instead of
<input type="text" id="stuff" name="stuff"/>
Tips when to use them?
No, there is no reason not to do this.
However, PHP is pretty much the only language which allows to create arrays like this - so if you ever change your backend to a different language you might have to change things.
It isn't a bad way. Typically programmers use array in such manner to post array with non-determined lenght. Still. Don't know for certain, but when You want to change method to GET then on IE <= 8 is a limit to 2048 chars in address lenght. And dynamic generated array can easy depleat this limit. On other browsers limit is much higher or there is none.
Another drawback of this method is that PHP will preceed correctly, but other server side languages may not. This isn't specified in official HTML docs, as far I know.
So it is more convinient to put it in a single cell in post array, that do subarray. If You want to do some namespacing, then You can write name in such way:
name="styff.text"
as do some of forum engines (for certain Vanilla 2 does).
If it has no diffrence to You I would stay to single variable name in html names. Mostly because of backend.
For tips how to use them I could recommend to use such array to cover dynamic generated content on site. Still it can be handled with normal names, but it is pretty ugly. If we have a case that You want to do a picture adding system, that I would name each input file with "pic[]" and on server iterate whole table.
The same thing for generating documents on client side. I would then do names like "content[][name]" "content[][type]" "content[][value]" and so on. Whathever I woud have in document part class I would throw in this kind of naming, and on server just check is set and do certain things for certain block of document.
This could be talked for a long time since every programmer have own technics and they tend to stick with it. For example I throw a in every form I have on site, and each action is parsed by a generall controller, and then passed by do specific controllers.
Nothing bad. If it is useful four you, use it.
Everytime I create a website for a client, I write the form HTML and then write the php script to handle that data. Sometimes the forms are long, sometimes there are multiple forms - it can get messy.
Before I begin to try and write my dynamic php form handler I'd really like some best practice advice and tips.
I thought of gathering all of the posted variables into an array to handle them. But then how do I know which values were supposed to be required or what they mean?
Maybe something already exists to fix this problem!
Thanks a lot,
Henry
Just a bit more info, what I have in mind is a php script which is flexible enough to work with any form built for it with any amount of inputs. I guess I see it as one file that sits on the server and multiple forms will be sending Ajax requests to it, which it can then satisfy
I don't think you should go with arrays, since the $_POST is already an array anyway.
But what about some sort of naming convention in your code?
ex:
<input type="text" name="txt_username" /> //prefix txt or whatever seems fitting.
Then use regular expressions to find what type of data you expect and act accordingly. You could for example write a class that handles different sorts of input and depending on the prefix in the name-property pass the data to the correct function.
Change the name of you submit button according to your form name. Then in php use a conditional statement to determine which form is posted and get your php working aas you wanted for different forms.
something like this
<input type="submit" name="signupform"/>
in php
if(isset($_POST['signupform']))
{
//Do this
}
elseif(isset($_POST['loginform']))
{
//do this
}
known issue:
You will need to keep those submit names unique and there should not be any other for element in any form being posted to that php file.
You can also add a hidden field
<input type="hidden" name='action' value='signup'/>
and then use a switch case with $_POST['action'] key.
I find it helps to seperate form parts by assigning them to an array e.g.
<input type="text" name="Users[username]" id="Users_username" />
That way, I can easily pick out sections by accessing the array key in php e.g.
$_POST['Users']; // returns username from above example
I'm not even sure if form arrays is the proper term, but it looks a bit like this:
<input name='element[]' type='text' />
<input name='element[]' type='text' />
Which is then retrieved in PHP as an array stored in $_POST['element'] -- in this case with 2 values.
I've tested it in the browsers I have available to me, but I've never seen this before and I'm wondering is this supported pretty much in all browsers? Or is this something very old that I've just not run into?
Thanks!
It is the server side language that turns this into an array (most languages don't require the name to end in [], that is an oddity of PHP).
As far as the browser is concerned, it is just a bunch of inputs with the same name, that get serialized using the standard rules for submitting form data. i.e.
element[]=value&element[]=value
No browser has any problems with this. It has worked this way since HTML first got a form element.