Ans: In this tutorial we will learn how to populate drop down menu from mysql and php.

Create categories table in mysql: 
Below is the structure of categories table with basic fields. 

CREATE TABLE `categories` (
`name` TEXT NULL,
PRIMARY KEY (`id`));

Suppose, Categories table have the records like:

Id        Name
1         HMTL
2         PHP
3         CSS
4         Jquery
5         Ajax

Create Connection(config.php) 
Connect to the database. In config.php add your database name, database username, database password and database name.

//Database details
$db_host = 'localhost';
$db_username = 'username';
$db_password = 'password';
$db_name = 'database_name';

//Create connection and select DB
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();


<?php require_once 'config.php';
<!DOCTYPE html>
<html lang="en">
        <title>Populating drop down menu from MySQL and PHP</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">      
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
                <h2 style="margin-bottom:50px;">Live Demo: Populating drop down menu from MySQL and PHP</h2>              
                <select name="category" id="category">
                    <option value=''>Select Category</option>
                    $sql = mysqli_query($conn, "SELECT * FROM categories ORDER BY id DESC LIMIT 20");
                    while ($row = mysqli_fetch_array($sql)) {
                        $id = $row['id'];
                        $name = $row['name'];
                        <option value='<?php echo $id; ?>'><?php echo $name; ?></option>
                    <?php } ?>

Written by
Check out this Author's contributed articles.
If you like Tutorialsmint and would like to contribute, you can also write an article using Write an Article. See your article appearing on the Tutorialsmint main page and help other programmers to enhance their knowledge.


Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Edit Post
Add Reply