Sometimes, when processing a form, you need to retrieve a number of values for a single variable. This is often a cause for confusion when beginning PHP. The particular problem faced: how do we process multiple values coming from a form to a databse, when using PHP?
Imagine we had a drop-down box containing a number of elements, and we want the user to select one or more. We’d use the select element in HTML.
Note the square brackets: for parameter arrays — parameters that allow multiple values — PHP requires that you name a GET or POST variable accordingly, so the select above needs to be named taglist[] in order to tell PHP that it will contain an array rather than a single value.
In order to process this, we then have to iterate over that array.
To iterate over the array in PHP code, we use something like this:
foreach($_POST["taglist[]"] as $s) { mysql_query("INSERT INTO articlestagged (article_id, tag) " . "VALUES ('$id','$s')") or die("Insert Error: ".mysql_error()); }Obviously this example relates to adding new entries to a database, but the same would apply if we were querying a database, displaying multiple images, or indeed anywhere else we needed to operate on multiple concurrent values.