Home >Database >Mysql Tutorial >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
Example Code
Combining the above steps, here's an example that connects to a MySQL database, executes the query, and generates a drop-down box with options:
By following these steps and using the provided code, you can easily populate a drop-down box with data from a MySQL table in PHP.
The above is the detailed content of How to Populate a Drop-Down Box with Data from a MySQL Query in PHP?. For more information, please follow other related articles on the PHP Chinese website!