Display Data From Database in Select Options using PHP & MYSQL

In this tutorial, You will learn to display data from the database in select options using PHP & MySQL with some simple steps. These steps are very easy to understand and implement in web applications.

Here, I have shared source code to display data in a single dropdown select option. Once you learn it, you will easily customize it according to your project requirements.php display data in select option

How to Fetch Data From Database in PHP and Display in Select Option

You should also learn the following examples –

1. Create Folder Structure

First of all, you should create the following folder structure –

codingstatus/
     |__database.php
     |__ fetch-data.php
     |__ display-data.php
     |

2. Insert Select Option Value

To display data from the database in a select option value, First of all, You will have to insert the select option value into the database. So, Make sure, you have already done it.

3. Connect Database to display data

To insert a select option value in the database, you must connect PHP to MySQL database with the help of the following query.

Where –

  • $hostName – It must contain hostname.
  • $userName – It must contain username of the database.
  • $password – It must contain password of the database
  • $database – It must contain database name.

File Name – database.php

<?php
$hostName = "localhost";
$userName = "root";
$password = "";
$databaseName = "codingstatus";
 $conn = new mysqli($hostName, $userName, $password, $databaseName);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>

4. Fetch Data From Database

To fetch data from database, you will have to implement the following steps –

Step-1:  Write SQL query to select from the “course”

Step-2: store option data in the $options by fetching from the database

File Name – fetch-data.php

<?php 
    $query ="SELECT courseName FROM courses";
    $result = $conn->query($query);
    if($result->num_rows> 0){
    	$options= mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
?>

5. Display Data in Select Option

To display data in select option, you will have to follow the following steps –

Step-1: First of all, Include database.php and then also include the fetch-data.php

Step-2: Apply foreach loop to the $option and print the option value within select option input field.

File Name – display-data.php

<?php
include("database.php");
include("fetch-data.php);
?>
<select name="courseName">
   <option>Select Course</option>
  <?php 
  foreach ($options as $option) {
  ?>
    <option><?php echo $option['courseName']; ?> </option>
    <?php 
    }
   ?>
</select>