How to Retrieve Data from a List Box with PHP



PHP


In this tutorial, we will show how to retrieve data from a list box with PHP.

There are 2 distinct type of list boxes in which we retrieve data from. The first is a list box that only allows one option to be selected. The second is a list box in which multiple options can be selected.

List boxes are common in web forms in which a webmaster wants to elicit information from a user. A user can either selection one option from a list box or multiple options, depending on the type of list box.

We will deal first with a list box in which only option can be selected.

Below is an example:





You have not selected any credit card.


You can see that the choice that you select gets updated.

HTML Code




PHP Code

The PHP to retrieve data from a list box is:

The $choice variable retrieves the selected option that the user has selected. If the $choice variable is set, meaning has a value, this value will be returned, and we will know which credit card the user selected. Otherwise, if no options have been selected, the statement is echoed that the user hasn't selected any credit cards.



List Box Where Multiple Options Can Be Selected

Now below is a list box where multiple options can be selected.






You haven't selected any foods to be in your salad.

HTML Code



PHP Code



In the first block of code, we use the $_POST superglobal array to retrieve all data from each of the options, which in this case is 3, tomatoes, cucumbers, and celery. This block of code is just to retrieve all the data, without knowing yet which data the user has selected.

In the second block of code, we use an if statement with the isset function to determine if the user has selected any options out of the list box. This checks all of the options of the list box to see if each is selected or not. Then we use the foreach command to go through each and every individual option. If the list box option is selected, the value attribute of that option is printed using the echo command. If no options are selected, the user sees a statement, "You haven't selected any foods to be in your salad."

Related Resources

How to Retrieve Data from a Text Box with PHP

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from a Check box with PHP

How to Retrieve Data from an Array of Checkboxes with PHP

How to Retrieve Data from a Drop-down List with PHP

How to Retrieve Data from a Textarea with PHP



HTML Comment Box is loading comments...