Dynamic Select Menus With PHP
When building content management systems, or most any web application, you often need to generate select menus dynamically by querying a database. A Select menu offers a user a set of predefined options to choose from, and prevent possible input errors that could occur if you instead gave the user a text field to type their selection, resulting in typos or selection of an option that is not available. A perfect example is when you have some list of categories stored in a table, and you need to create a form that allows a user to add a new record in a particular category. Here's what your table may look like:
A unique category Id is used as the primary key, creating a practical method of referencing a category. To query this table and generate a select menu, we can use a while loop like this:
Notice that the select tags need to be written before and after the loop, so you don't end up with multiple menus, but just one menu
with many options. This approach is practical for future maintenance too, as you can simply add a new category to your database, and the interface will include it automatically.
The above example works great for building a menu on an add page where the user has not yet selected an option and stored it in a database,
but if you were creating an edit page you would need to have the user's previous selection already shown in the menu.to do this you would need to dynamically write in the selected="selected" attribute/value pair in the option tag for the category selected. Assume we have an articles table that has a CatID field that relates to our category table. To find out which option was selected we'll compare the CatID in the articles table and the CatID in the categories table as we run a loop to build the menu. We'll need to run two queries, one to get the articles record (in this demo I'll hard code in the id of the article we want) and one to get the categories.
The $selected variable stores our attribute/value pair needed to preselect the user's option stored in the database, and will be empty if the condition was not met, thus leaving the option tag untouched.
Yet another common, dynamic select menu scenario is displaying date selections for years, months, or days. I create an external arrays file that has associative arrays of common lists such as this. Here is what such a file might look like. You could also add things like credit cards your e-commerce system accepts, and a list of countries for shipping information forms. Looping through associative arrays like this is a little different.
A foreach loop is the most convenient approach for associative arrays, giving you easy access to the key and the value of each item in the array.
There are an infinite number of applications for these examples, whether you are building a contact form or an entire content management system. Hope you find them useful!




