Filling a Dropdown List with Data from a MySQL Table in PHP
In PHP, populating a dropdown list with the results of a MySQL query can be a straightforward task. However, it's essential to understand the process to ensure proper functionality.
Query Execution
You begin by executing your query to retrieve data from the MySQL table. In this case, your query is:
SELECT PcID FROM PC;
Database Connection
Before executing the query, you need to establish a connection to your MySQL database. Make sure you set the correct username and password based on your specific setup. For instance, if you're using a testing environment like WAMP, you may need to set the username as "root."
Looping Over Results
Once the query is executed, you use a loop to iterate through the resulting rows. For each row, you create an
Dropdown Output
Finally, you wrap these
Complete Code Sample
Here's an example of complete PHP code that connects to a MySQL database, executes the specified query, and outputs a dropdown list filled with the retrieved data:
<?php // Database connection details mysql_connect('hostname', 'username', 'password'); mysql_select_db('database-name'); // SQL query $sql = "SELECT PcID FROM PC"; $result = mysql_query($sql); // Start dropdown list echo "<select name='PcID'>"; // Loop through results and create options while ($row = mysql_fetch_array($result)) { echo "<option value='" . $row['PcID'] . "'>" . $row['PcID'] . "</option>"; } // End dropdown list echo "</select>"; ?>
The above is the detailed content of How to Populate a Dropdown List with Data from a MySQL Table in PHP?. For more information, please follow other related articles on the PHP Chinese website!