html drop down with search from table php mysql

To create an HTML dropdown with a search functionality that fetches data from a MySQL table using PHP and displays it with Bootstrap styling, you can follow these steps: Learn more How to SUM Columns value in MYSQL

  1. Set up the MySQL database and table (assuming you already have a database and table ready).
  2. Create a PHP script to fetch the data from the MySQL database.
  3. Use Bootstrap and jQuery for the searchable dropdown.

Step 1: Set Up the MySQL Database

Let’s assume you already have a database called sample_db and a table called items with the following structure:

CREATE DATABASE sample_db;
USE sample_db;

CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

INSERT INTO items (name) VALUES
('Item 1'),
('Item 2'),
('Item 3'),
('Item 4'),
('Item 5');

Step 2: Create the PHP Script

Create a PHP file (e.g., index.php) to fetch data from the MySQL database and display it in a Bootstrap-styled searchable dropdown.

<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sample_db";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch data from the items table
$sql = "SELECT id, name FROM items";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Searchable Dropdown</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css">
</head>
<body>
<div class="container">
    <h2 class="mt-5">Searchable Dropdown</h2>
    <form>
        <div class="form-group">
            <label for="itemSelect">Select an Item</label>
            <select id="itemSelect" class="selectpicker form-control" data-live-search="true">
                <?php
                if ($result->num_rows > 0) {
                    while($row = $result->fetch_assoc()) {
                        echo "<option value='" . $row["id"] . "'>" . $row["name"] . "</option>";
                    }
                } else {
                    echo "<option>No items found</option>";
                }
                ?>
            </select>
        </div>
    </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>
</body>
</html>

<?php
$conn->close();
?>


Leave a Reply