user1278496
user1278496

Reputation: 1066

Populate a drop down box with values from database using php and sql

I want to have a drop down box that has a list of different sizes of item. I have a table called items in my database with an attribute inside it called sizes. This maps to a table called sizes which lists the different sizes with different prices etc.

I simply want to create a drop down box within the items web page which lists the sizes associated with that item. How can I use php to fetch the sizes and display them in a drop down box?

I have got items table which has a composite key of item_id and size_id which is mapped to sizes table which has a primary key of size_id.

I have tried to find information from the net but to no avail.

Thanks

Upvotes: 1

Views: 5822

Answers (2)

Codeeater
Codeeater

Reputation: 51

You can write two queries or you can use join to fetch values from both the tables at a time.. But for that I would like to know what type of mapping are you using between items table and sizes table..

Upvotes: 0

Dumbo
Dumbo

Reputation: 14142

You can use HTML's SELECT and its OPTION something like:

<select name="mySelect"> 
    <?php $result= mysql_query('SELECT * FROM items'); ?> 
    <?php while($row= mysql_fetch_assoc($result)) { ?> 
        <option value="<?php echo htmlspecialchars($row['your_column_name']);?>"> 
            <?php echo htmlspecialchars($row['your_column_name']); ?> 
        </option> 
    <?php } ?> 
</select> 

Of course, you can add a ORDER BY ... to the sql query above for sorting. Then depending on your form method, you can access this by using $_POST["mySelect"] or $_GET["mySelect"]

Upvotes: 4

Related Questions