Retrieve select box value from database using PHP
I have been in many situations in designing a html form where i want the value stored in database selected in select box when editing the user data.
For example if i have colors like Red, Green, Blue, Yellow, Violet shown in selectbox and if the user selected Green and previously stored in database, then we need to show the select box with Green as selected value. This kind of situation arises, while editing or making changes to database content.
Here is the very simple php code to accomplish that task.
First we hold all select box colors in an array, then we compare each array element to the value stored in database. If it matches, then we output selected option else we output unselected option. In this way all the selectbox options are shown with selected one.
<select name="color">
<?php
//Array of colors for selectbox
$aColors = array("Red", "Blue", "Green", "Yellow", "Violet");
$dbcolor = "Yellow"; // stored in database
foreach ($aColors as $color)
{
if($color == $dbcolor) {
echo "<option value=\"$color\" SELECTED>$color</option>";
} else
{
echo "<option value=\"$color\">$color</option>";
}
}
?>
</select>
Similar Posts:
- how to store and retrieve checkbox value in php?
- MySQL Query to Select Random Records
- How URL shortening scripts work?
- Tutorial: How to write a Wordpress Plugin?
- How to filter & escape data from Injection attacks in PHP!
- Fix: Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’
- Rewriting MySQL Date to PHP Date Format
- Where does wordpress store htaccess rewrite rules?
- how to get selected textarea value using javascript
- How to manually upgrade wordpress from older versions


June 14, 2009
Great post! I have been looking how to do this! Thanks!