Jump to content

Dropdown from mysql table


dropbop

Recommended Posts

Hi,

 

I don know how to explain this in words too well, so i have create 2 images to show what I need.

 

What I need to do is use whats in the first image (table.jpg)(the database) to create whats in the second image (dropdown.jpg)(the drop-down menu)

 

The results of the form will be entered into the database.  category_id will be the value thats inserted.

 

Many kind regards

 

Eoin

 

 

 

 

 

[attachment deleted by admin]

Link to comment
https://forums.phpfreaks.com/topic/250210-dropdown-from-mysql-table/
Share on other sites

Okay this is achieved using while loops,

 

here is the php code to do what you asked, i havn't done it to look like your Jpg but i have done it so it will show the categories and sub-categories in order.

 

hopefully you can modify this to your needs.

 

<?php

//This selects all rows where Parent_id = 0 and ORDERS by category_name
$parent_query = mysql_query("SELECT * FROM cat WHERE parent_id=0 ORDER BY category_name ASC");
while($parent=mysql_fetch_array($parent_query)){
    $parent_id = $parent['category_id'];
    echo $parent['category_name'];
    echo "<br/>";
    
    //This gets all the rows where the PARENT_ID = the parents category_id
    $child_query = mysql_query("SELECT * FROM cat WHERE parent_id=$parent_id ORDER BY category_name ASC");
while($child=mysql_fetch_array($child_query)){
    echo $child['category_name'];
    echo "<br/>";
}
echo "<br/>";
}

?>

 

Seany123

Ok, here is the finished product...

 

Using the code Seany provided (which I am very grateful for), I have created the dropdown as follows... Below is a jpg of the finished dropdpown

<select style="width:150px;" name="category">
<option value="">Select a Category</option>
<?php

//This selects all rows where Parent_id = 0 and ORDERS by category_name
$parent_query = mysql_query("SELECT * FROM categories WHERE parent_id=0 ORDER BY category_name ASC");
while($parent=mysql_fetch_array($parent_query)){
    $parent_id = $parent['category_id'];
$parent_name = $parent['category_name'];
echo "<option style=\"font-weight:bold;\">".$parent_name."</option>";
    
    //This gets all the rows where the PARENT_ID = the parents category_id
    $child_query = mysql_query("SELECT * FROM categories WHERE parent_id=$parent_id ORDER BY category_name ASC");
while($child=mysql_fetch_array($child_query)){
$child_id = $child['category_id'];
$child_name = $child['category_name'];

echo "<option style=\"padding-left:15px;\" value=\"".$child_id."\">".$child_name."</option>";
  }
}

?>
</select>

 

 

 

[attachment deleted by admin]

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.