Skip to content
Advertisement

Populate a Drop down box from a mySQL table in PHP

I am trying to populate a Drop down box from results of a mySQL Query, in Php. I’ve looked up examples online and I’ve tried them on my webpage, but for some reason they just don’t populate my drop down box at all. I’ve tried to debug the code, but on the websites I looked at it wasn’t really explained, and I couldn’t figure out what each line of code. Any help would be great 🙂

Here’s my Query: Select PcID from PC;

Advertisement

Answer

You will need to make sure that if you’re using a test environment like WAMP set your username as root. Here is an example which connects to a MySQL database, issues your query, and outputs <option> tags for a <select> box from each row in the table.

<?php

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

$sql = "SELECT PcID FROM PC";
$result = mysql_query($sql);

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

?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement