Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP Dropdowns

Status
Not open for further replies.

gokeeffe

Programmer
Jan 11, 2005
170
IE
Hi

Could someone please point me in the direction of where I could find an example of someone using PHP to dynamically populate dropdown boxes.

Example dropdown 2 depends on dropdown 1 and 3 depends on dropdown 2 etc..

I have been told to use PHP to do this as some users may have Javascript turned off, if I were to use a Javascript approach. (Also I find Javascript difficult and cannot understand examples I have found.)

Please bear in mind that the dropdown info is being pulled from a mysql database.

Am I right to believe that PHP is the best approach and not Javascript.

Regards & Thanks

Graham
 
Retrieving data:
faq434-3850

Building the dropdown:
In the loop that retrieves the data print statements create the <option> tags. They should also indicate the 'selected' state upon rebuilding the page.
In the example the column with the label is $row['label'], the $row['ovalue'] is the option value.
Code:
# I assume $result is the resource ID
# We'll collect the output in a variable
while ($row = mysql_fetch_assoc($result)){
   # start option tag
   $output .= "<option";
   # check for selected
   if ($_POST['selectvar1'] == $rowp'ovalue']){
      $output .= " selected";
   }
   $output .= ">".$row['label']."</option>\n";
}
# embed into the select tag
echo '<select name="selectvar1">';
echo $output;
echo '</select>';
This is it in principle.
 
PHP is server side, Javascript is client side. If you want to change the contents of dropdown lists on the client side, you have to at least use a touch of Javascript in the onChange event handler for the primary dropdown. To avoid having to use any more JS, you have to submit the form to the server, then use PHP to read the contents of the controlling one to create the next one, and then spit out the new page.

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top