Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching data from MySQL database to html dropdown list

I have a web site that contains an HTML form, in this form I have a dropdownlist with list of agents that works in the company, I want to fetch data from MySQL database to this dropdownlist so when you add a new agent his name will appear as an option in the drop down list.

<select name="agent" id="agent">
</select>  
like image 514
ziz194 Avatar asked Apr 04 '12 10:04

ziz194


People also ask

How do you display data in a dropdown database?

To do that we create a connection string object to connect the database with the application and read data from the database using the select command to display data in the DropDownList. All you have to do is implement and hook it up to your requirement or need.


2 Answers

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.htmlspecialchars($row['something']).'">'.htmlspecialchars($row['something']).'</option>';
}

echo '</select>';// Close your drop down box
like image 123
SpaceBeers Avatar answered Sep 24 '22 16:09

SpaceBeers


# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly
like image 44
yasin Avatar answered Sep 23 '22 16:09

yasin