Home >Database >Mysql Tutorial >How to Populate a Drop-Down Box with Data from a MySQL Query in PHP?

How to Populate a Drop-Down Box with Data from a MySQL Query in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 12:45:02307browse

How to Populate a Drop-Down Box with Data from a MySQL Query in PHP?

Selecting Options for a Drop-Down Box from MySQL in PHP

Filling a drop-down box with data from a MySQL query can be a challenge for those new to PHP programming. This comprehensive guide will provide a step-by-step explanation to help you achieve this task.

Connecting to MySQL and Executing the Query

Establishing a connection to the MySQL database is crucial. In the code snippet below, we replace the placeholder values with your specific credentials:

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

Once the connection is established, we execute the SQL query to retrieve the data you need:

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

Generating Drop-Down Options

To populate the drop-down box, we loop through each row in the query result:

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

In each iteration, we create an