Populate a Drop down box from a mySQL table in PHP
You can use the PHP MySQLi extension to connect to a MySQL database and retrieve the data from a table to populate a drop-down box.
You can use the PHP MySQLi extension to connect to a MySQL database and retrieve the data from a table to populate a drop-down box. Here's an example:
Example of using the PHP MySQLi extension to connect to a MySQL database and retrieve the data from a table to populate a drop-down box
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM mytable";
$result = $conn->query($sql);
echo "<select>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
$conn->close();
?>
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
You can use the above code snippet to populate your dropdown box. Replace "mytable" with the name of your table, and "id" and "name" with the appropriate column names from your table.