Populate a Drop down box from a mySQL table in PHP

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>";

?>

Leave a Comment