Jump to content

Dynamically build a Drop down List


Chunk78

Recommended Posts

Hi

 

I'm a newbie to php and I'm struggling with the following problem:

 

I am using php/mySQL to display a photo gallery.  I have it working OK at the moment if I want to display all photos from the database. However I would like to smarten up the page a bit. 

 

Each of the photos in the database are arranged into catagories so I would like to use a drop down menu to allow the user to filter the photos by Catagory.

 

My plan would be to build a drop-down menu based on the catagories stored in the database.  The user would select the catagory then use a submit button to rebuild the page with the new filter as part of the query.

 

1) How do I dynamically build a drop-down menu.

2) If the user selects an option from the drop-down menu how do I store the value selected and use it to filter the MYSQL query.  I have no problem with the MySQL syntax for this, just using the selected Value.  I also want to redisplay the option chosen by user

 

I hope the above makes sense

 

I would appreciate it if somebody could point me in the right direction

 

Many Thanks

Link to comment
https://forums.phpfreaks.com/topic/55390-dynamically-build-a-drop-down-list/
Share on other sites

Ok, i suggest you make a table in your database containing all of the categories, then to build your drop down box:

 

<select name="category">
<?php
$sql = mysql_query("SELECT * from `categories`") or die(mysql_error());
while($row = mysql_fetch_assoc($sql)){
echo '<option value="'.$row['category'].'">'.$row['category'].'</option>';
}
?>
</select>

 

Then just retreive the category from the post array:

 

<?php
$category = $_POST['category'];
$sql = mysql_query("SELECT * FROM `photos` WHERE `category`='$category'") or die(mysql_error());
?>

The above routine posted by GingerRobot would work but you can go one step further by making the option selected by the user be selected.

 

<?php
$useroption=$_POST['category']; //Get the option selected by the user
$options='';
$sql=mysql_query("SELECT * FROM `categories` ORDER BY `name` ASC");
while ($row=mysql_fetch_assoc($sql)) {
  $options.='<option value="'.$row['categoryid'].'"'.($row['categoryid']==$useroption ? ' SELECTED="SELECTED"' : '').'>'.$row['name'].'</option>';
}
?>

 

Then your HTML could look like:

Categories: <select name="category"><?=$options?></select>

 

The interesting part is:

($row['categoryid']==$useroption ? ' SELECTED="SELECTED"' : '')

 

It's the same as:

if ($row'categoryid']==$useroption) {echo ' SELECTED="SELECTED"';}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.