Different Ways of Populating HTML Select Options from MySQL Database using PHP, JS, and jQuery Tutorial

In this tutorial, you will learn how to Populate the HTML's Select box with options from the MySQL Database. The main purpose of this tutorial is to provide the students and beginners with a reference for learning some techniques for building an application using PHP, MySQL DB, JS, and jQuery Library. Here, snippets and scripts are provided to give you a better understanding of the possible ways to achieve the said goal of this tutorial. A sample source code zip file is also provided and is free to download.

What is HTML Select?

The HTML Select (<select></select>) is an element used for creating a drop-down list. It is used for form fields that have multiple options or possible values. It is commonly used in forms to collect user input.

How to Populate HTML Select with Option From MySQL Database?

There are a lot of ways to populate the HTML Select box with options listed from the MySQL Database. Using The PHP code, we can simply retrieve the data from the Database and use the retrieved data as the select field option.

Here are the following possible and effective ways to Populate Select with data from MySQL DB:

  1. Straightforward Coding using HTML and PHP
  2. Using JavaScript
  3. Using JavaScript Fetch API
  4. Using jQuery
  5. Using jQuery Ajax Request

The list above is all effective and can be achieved easily achieve in just a short line of code. Options 3 and 5 are commonly used when the data of the form page are being retrieved using API requests.

Here are the following snippets or scripts of how you can achieve our for this tutorial using the listed possible ways.

Examples

Assuming that we have the following Database Schema which contains some list of countries. The data on the countries table is the data that we will use as the options of the HTML Select element.

  1. CREATE TABLE `countries` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(250) NOT NULL
  4. INSERT INTO `countries` (`id`, `name`) VALUES
  5. (1, 'Singapore'),
  6. (2, 'Peru'),
  7. (3, 'Belgium'),
  8. (4, 'United States'),
  9. (5, 'United Kingdom'),
  10. (6, 'Indonesia'),
  11. (7, 'Ireland'),
  12. (8, 'India'),
  13. (9, 'Netherlands'),
  14. (10, 'Nigeria'),
  15. (11, 'Pakistan'),
  16. (12, 'Sweden'),
  17. (13, 'Canada'),
  18. (14, 'Germany'),
  19. (15, 'Mexico'),
  20. (16, 'New Zealand'),
  21. (17, 'Australia'),
  22. (18, 'Colombia'),
  23. (19, 'Chile'),
  24. (20, 'Italy'),
  25. (21, 'China'),
  26. (22, 'Poland'),
  27. (23, 'South Africa');
  28. ALTER TABLE `countries`
  29. ADD PRIMARY KEY (`id`);
  30. ALTER TABLE `countries`

Database Connection

Here are the PHP scripts that handle the Database Connection between the application and MySQL Database.

db-connect.php

  1. <?php
  2. $host = "localhost";
  3. $username = "root";
  4. $password = "";
  5. $dbname = "sample_db";
  6.  
  7. $conn = new MySQLi($host, $username, $password, $dbname);
  8.  
  9. if(!$conn){
  10. die("Database Connection failed. Error: ". $conn->error);
  11. }

The example script below that I provided is using the Bootstrap 5.3 Framework Library for the design.

Example 1: Straightforward Coding using HTML and PHP

Here's an example script that demonstrates the straightforward technique to list the DB data on the HTML Select element. The script is written in combined HTML and PHP scripts.

  1. <?php ;
  2. require_once('db-connect.php');
  3. $countries_qry = $conn->query("SELECT * FROM `countries` order by `name` asc");
  4. $countries = $countries_qry->fetch_all(MYSQLI_ASSOC);
  5. ?>
  6. <div class="card rounded-0 shadow mb-3">
  7. <div class="card-header rounded-0">
  8. <div class="card-title"><b>Using HTML5</b></div>
  9. </div>
  10. <div class="card-body rounded-0">
  11. <div class="container-fluid">
  12. <div class="mb-3">
  13. <label class="fw-light text-body">Populating Select Options: Example #1</label>
  14. <select class="form-select rounded-0" name="select1" id="select1">
  15. <?php
  16. $default = mt_rand(1, count($countries));
  17. $countries = $conn->query("SELECT * FROM `countries` order by `name` asc");
  18. while($row = $countries->fetch_assoc()):
  19. if($default == $row['id'])
  20. echo "<option value='{$row['id']}'>{$row['name']}</option>";
  21. else
  22. echo "<option value='{$row['id']}'>{$row['name']}</option>";
  23. endwhile;
  24. ?>
  25. </select>
  26. </div>
  27. </div>
  28. </div>
  29. </div>
  30. <?php $conn->close(); ?>

The script above will result in something like the following image:

Populating SELECT Element with Data from MySQL Database

Example 2: Using JavaScript

We can also populate the list option data of the select element using JavaScript due to any instance that we need to meet our requirements. We can simply set the data into the JS script as a JSON encoded string and parse it using the JS JSON.parse and create an option element and append it into the select element. See the following example script.

  1. <?php ;
  2. require_once('db-connect.php');
  3. $countries_qry = $conn->query("SELECT * FROM `countries` order by `name` asc");
  4. $countries = $countries_qry->fetch_all(MYSQLI_ASSOC);
  5. $countries_json = json_encode($countries);
  6. ?>
  7.  
  8. <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 mx-auto">
  9. <div class="card rounded-0 shadow mb-3">
  10. <div class="card-header rounded-0">
  11. <div class="card-title"><b>Using JavaScript</b></div>
  12. </div>
  13. <div class="card-body rounded-0">
  14. <div class="container-fluid">
  15. <div class="mb-3">
  16. <label class="fw-light text-body">Populating Select Options: Example #2</label>
  17. <select class="form-select rounded-0" name="select2" id="select2"></select>
  18. </div>
  19. </div>
  20. </div>
  21. </div>
  22. </div>
  23.  
  24. var countries = '<?= $countries_json ?>';
  25. var pjs_countries = JSON.parse(countries);
  26.  
  27. const select2 = document.getElementById('select2')
  28. /**
  29. * Populating Select Field : Example #2 (PURE JS)
  30. */
  31. Object.keys(pjs_countries).map(function(k){
  32. var option = document.createElement('option')
  33. option.setAttribute('value', pjs_countries[k].id)
  34. option.innerText = pjs_countries[k].name
  35. select2.appendChild(option)
  36. })
  37. // set default Selected
  38. select2.value = Math.floor(Math.random() * (pjs_countries.length - 1 ) + 1)
  39. <?php $conn->close(); ?>

Here's the output of the script.

Populating SELECT Element with Data from MySQL Database

Example 3: Using jQuery

This option or way is like Example #2 but only written in JS script using the jQuery Library methods and functions.

  1. <?php ;
  2. require_once('db-connect.php');
  3. $countries_qry = $conn->query("SELECT * FROM `countries` order by `name` asc");
  4. $countries = $countries_qry->fetch_all(MYSQLI_ASSOC);
  5. $countries_json = json_encode($countries);
  6. ?>
  7. <div class="card rounded-0 shadow mb-3">
  8. <div class="card-header rounded-0">
  9. <div class="card-title"><b>Using jQuery</b></div>
  10. </div>
  11. <div class="card-body rounded-0">
  12. <div class="container-fluid">
  13. <div class="mb-3">
  14. <label class="fw-light text-body">Populating Select Options: Example #3</label>
  15. <select class="form-select rounded-0" name="select3" id="select3"></select>
  16. </div>
  17. </div>
  18. </div>
  19. </div>
  20. var countries = '<?= $countries_json ?>';
  21. /**
  22. * Using jQuery: Example #3
  23. */
  24. var jq_Countries = $.parseJSON(countries)
  25. const select3 = $('#select3')
  26. jq_Countries.forEach(data => {
  27. var option = $('<option>')
  28. option.attr('value', data.id)
  29. option.text(data.name)
  30. select3.append(option)
  31. })
  32.  
  33. // set default Selected
  34. select3.val(Math.floor(Math.random() * (pjs_countries.length - 1 ) + 1))
  35. <?php $conn->close(); ?>

Here's the output of the script above.

Populating SELECT Element with Data from MySQL Database

Example 4: Using JavaScript Fetch API

Using JS API is also one of the possible ways to populate the select element using the data from the database. This way can be used if you wish to retrieve the database data using HTTP Request and JavaScript without any JS library.

  1. <div class="card rounded-0 shadow mb-3">
  2. <div class="card-header rounded-0">
  3. <div class="card-title"><b>Using JS Fetch API</b></div>
  4. </div>
  5. <div class="card-body rounded-0">
  6. <div class="container-fluid">
  7. <div class="mb-3">
  8. <label class="fw-light text-body">Populating Select Options: Example #4</label>
  9. <select class="form-select rounded-0" name="select4" id="select4"></select>
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. /**
  15. * Using JS Fetch API: Example 4
  16. */
  17. const select4 = document.getElementById('select4')
  18. fetch('api.php')
  19. .then(response => { return response.json()})
  20. .then(data => {
  21. data.forEach(country => {
  22. var option = document.createElement('option')
  23. option.setAttribute('value', country.id)
  24. option.innerText = country.name
  25. select4.appendChild(option)
  26. })
  27.  
  28. // set default Selected
  29. select4.value = (Math.floor(Math.random() * (data.length - 1 ) + 1))
  30. })

api.php

  1. <?php
  2. require_once('db-connect.php');
  3. $countries_qry = $conn->query("SELECT * FROM `countries` order by `name` asc");
  4. $countries = $countries_qry->fetch_all(MYSQLI_ASSOC);
  5. echo json_encode($countries);
  6. $conn->close();

Populating SELECT Element with Data from MySQL Database

Example 5: Using jQuery's Ajax Request

Here's another example of populating the select element with MySQL Database data using Ajax Request.

  1. <div class="card rounded-0 shadow mb-3">
  2. <div class="card-header rounded-0">
  3. <div class="card-title"><b>Using jQuery's Ajax</b></div>
  4. </div>
  5. <div class="card-body rounded-0">
  6. <div class="container-fluid">
  7. <div class="mb-3">
  8. <label class="fw-light text-body">Populating Select Options: Example #5</label>
  9. <select class="form-select rounded-0" name="select5" id="select5"></select>
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. /**
  15. * Using jQuery's Ajax Request: Example 5
  16. */
  17. const select5 = $('#select5')
  18. $.ajax({
  19. url:'api.php',
  20. dataType:'json',
  21. error: err=>{
  22. console.error(err)
  23. },
  24. success: function(resp){
  25. resp.forEach(data => {
  26. var option = $('<option>')
  27. option.attr('value', data.id)
  28. option.text(data.name)
  29. select5.append(option)
  30. })
  31. select5.val(Math.floor(Math.random() * (resp.length - 1 ) + 1))
  32. }
  33. })

api.php

  1. <?php
  2. require_once('db-connect.php');
  3. $countries_qry = $conn->query("SELECT * FROM `countries` order by `name` asc");
  4. $countries = $countries_qry->fetch_all(MYSQLI_ASSOC);
  5. echo json_encode($countries);
  6. $conn->close();

Populating SELECT Element with Data from MySQL Database

There you go. It's up to you which way or technique you prefer to use or suits your current project. I have also provided the source code zip file that I created for this tutorial. You can download it for free on this site. The download button is located below this tutorial's content.

That's it! I hope this Different Ways of Populating HTML Select Options from MySQL Database using PHP, JS, and jQuery Tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment