Nikos Bounas Nikos Bounas - 3 months ago 8
HTML Question

How can I show values of a database in select options?

I want to select the values of my table of database with html select option. I want to do this with php-mysql. How can I do that?

Answer

Follow the below code.

<?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 name FROM state";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
?>
<select name="myCountry">
<?php
    // output data of each row
    while($row = $result->fetch_assoc()) {
    ?>
    <option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
    <?php
    }
    ?>
</select>
<?php
}
$conn->close();
?>
Comments