Collecting data from a Multiple Select with PHP

This script teaches the technique necessary to access the selected elements of a multiple select.

Perhaps a problem that can arise when working with PHP is wanting to collect the data from a Multiple Select. Remember that a multiple select is a form field where several elements can be selected at the same time.

Note: To select several elements of a multiple select field, we have to use the “control” button and click on each of the elements that we want to select. It is important that this point is clear to the visitors of your pages, since it is very common for users not to know how to handle these types of fields.

To better see what we want to do, it is very interesting.

To continue, let’s take a look at the following example…

First name:
Last name:
Email:
Beer:

We have this form on our page and we want to collect the data entered by the user. For the fields “name”, “surname” and “email” we do not have any kind of problem, we collect the data by the usual method, that is:

Last Name: “. $_POST; echo “
Email: “. $_POST ; ?>

One might ask, and why can’t I put “$cerveza=$_POST”? The problem is that the options of the multiple select all have the same name and in case of having several selected elements we would only obtain the last element. And how to solve this? Well, the solution is quite simple. It is enough to put some brackets () at the end of the field name of the multiple select, in our case it would be “beer”. In this way, PHP interprets the field in question as an array with as many positions as there are elements selected in the multiple select. So let’s see how our example would look…

See also  Dotted line with Photoshop CC

First name:
Last name:
Email:
Beer:

And to collect the information and treat it we would act as follows…

Last Name: “. $_POST; echo “
Email: “. $_POST ; $beers=$_POST; //we go through the array of selected beers. Do not forget that the first position of an array is 0 for ($i=0;$i Beer ” . $i . “: ” . $beers; } ?>

Note: When putting this type of name (ending in brackets) to a form field and if we use Javascript functions to validate, handle, etc… we must add to said field, in addition to the name, the HTML id attribute and use the latter as the field identifier, instead of the name that has been placed in the name attribute, since that would cause problems.

The complete code of this example could be the following. It would be nice to note that we have put all the code in a PHP file. That code has a reentrant form, that is, the page calls itself to process the form. Remember that you can see this .

First name:
Last name:
Email:
Beer:

Last Name: “. $_POST; echo “
Email: “. $_POST ; $beers=$_POST; //we go through the array of selected beers. Do not forget that the first position of an array is 0 for ($i=0;$i Beer ” . $i . “: ” . $beers; } } ?>

Loading Facebook Comments ...
Loading Disqus Comments ...