I’m giving myself a crash course in PHP. I’m puzzled by one particular bit of advice in my PHP textbook and I was hoping for a second opinion.
Imagine a table of personal details for the user to enter on a single page. What I ultimately want is a form like this, albeit dynamically generated.
When the user clicks ‘Submit’, all the personal details entered in the table will be submitted, along with the state of all the checkboxes. There is a variable number of rows in the table of personal details (in practice only 10-20).
The question is how to submit the array of checkboxes and text boxes. My PHP book suggests doing things this way for the checkboxes:
<input type="checkbox" name="select_name[]" value="1" checked />
<input type="checkbox" name="select_name[]" value="2" checked />
...
However surely this
<input type="checkbox" name="select_name[1]" checked />
<input type="checkbox" name="select_name[2]" checked />
...
is simpler?
- The process of accessing the checkbox values in PHP seems to be simpler in the second case:
$my_array = $_POST['select_name'];
echo $my_array[1];
Whereas in the first case, I have to worry about the array possibly being empty before I access individual elements.
2. The first method doesn’t work for text boxes. So the second method has the advantage of consistent syntax between accessing the text boxes and accessing the checkboxes.
Am I missing something?
Is the advantage solely that, with method 1, you can ascertain the number of checkboxes checked? (if we didn’t already know that server-side?)
To confuse things further, after Googling the subject, I’ve seen a few suggestions that to submit arrays of text boxes, you have to do something contrived with hidden forms, or serialise the array then ‘de-serialise’ it again (?!) … so I have a niggling concern that there might be a problem with the way I’m doing it…?
Thanks in advance!