Create a drop-down list that options fetched from a MySQL database in PHP
Last Updated :
06 Aug, 2024
In many scenarios, we may need to create a dropdown input that can display all the options consistent with the current state of the database. This form of input is used many times in real life and the following examples may help to understand the same.
- A set of students who have unique registration numbers.
- A set of branch names and their branch ids.
- A list of categories to which a particular product must belong.
In this article, we will create a drop-down with a list of categories to which a particular product must belong.
Approach: In each of these examples, if we use a drop-down menu that fetches data from the database the user will be able to enter data more accurately and the UI will be more user-friendly.Â
We need the following
- A database with a table of categories and another table of products with a foreign key to the category ID to which the particular product belongs.
- HTML form that accepts the data.
Steps:
Database creation:
- Switch on Apache and MySQL from the XAMPP control panel.
Click on "Start" buttons- Create a database "example_store" by clicking on the new button.
- Enter the database name and click "Create".
- Click on the SQL tab and paste the following code and click "GO".
MySQL queries:
-- Table structure for table `category`
CREATE TABLE `category` (
`Category_ID` int(11) NOT NULL,
`Category_Name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Dumping data for table `category`
INSERT INTO `category` (`Category_ID`, `Category_Name`) VALUES
(1, 'Category A '),
(2, 'Category B');
-- Table structure for table `product`
CREATE TABLE `product` (
`Product_ID` int(11) NOT NULL,
`product_name` varchar(255) NOT NULL,
`category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Dumping data for table `product`
INSERT INTO `product` (`Product_ID`, `product_name`, `category_id`) VALUES
(1, 'Product A1', 1),
(2, 'Product A2', 1),
(3, 'Product B1', 2);
-- Primary Key Constraints
ALTER TABLE `category`
ADD PRIMARY KEY (`Category_ID`);
ALTER TABLE `product`
ADD PRIMARY KEY (`Product_ID`),
ADD KEY `Category_constraint` (`category_id`);
-- AUTO_INCREMENT for table `category`
ALTER TABLE `category`
MODIFY `Category_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
-- AUTO_INCREMENT for table `product`
ALTER TABLE `product`
MODIFY `Product_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
-- Foreign Key Constraints
ALTER TABLE `product`
ADD CONSTRAINT `Category_constraint` FOREIGN KEY (`category_id`)
REFERENCES `category` (`Category_ID`) ON DELETE
CASCADE ON UPDATE CASCADE;
Example: We create a PHP file in a folder called "example_store" in htdocs and create the following form.php webpage which can be accessed in a browser at "localhost/example_store/form.php".
PHP
<?php
// Connect to database
$con = mysqli_connect("localhost","root","","example_store");
// mysqli_connect("servername","username","password","database_name")
// Get all the categories from category table
$sql = "SELECT * FROM `category`";
$all_categories = mysqli_query($con,$sql);
// The following code checks if the submit button is clicked
// and inserts the data in the database accordingly
if(isset($_POST['submit']))
{
// Store the Product name in a "name" variable
$name = mysqli_real_escape_string($con,$_POST['Product_name']);
// Store the Category ID in a "id" variable
$id = mysqli_real_escape_string($con,$_POST['Category']);
// Creating an insert query using SQL syntax and
// storing it in a variable.
$sql_insert =
"INSERT INTO `product`(`product_name`, `category_id`)
VALUES ('$name','$id')";
// The following code attempts to execute the SQL query
// if the query executes with no errors
// a javascript alert message is displayed
// which says the data is inserted successfully
if(mysqli_query($con,$sql_insert))
{
echo '<script>alert("Product added successfully")</script>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="POST">
<label>Name of Product:</label>
<input type="text" name="Product_name" required><br>
<label>Select a Category</label>
<select name="Category">
<?php
// use a while loop to fetch data
// from the $all_categories variable
// and individually display as an option
while ($category = mysqli_fetch_array(
$all_categories,MYSQLI_ASSOC)):;
?>
<option value="<?php echo $category["Category_ID"];
// The value we usually set is the primary key
?>">
<?php echo $category["Category_Name"];
// To show the category name to the user
?>
</option>
<?php
endwhile;
// While loop must be terminated
?>
</select>
<br>
<input type="submit" value="submit" name="submit">
</form>
<br>
</body>
</html>
Output:
- The drop-down currently shows only Category A and Category B.If we add few more Categories in the Database, we get them displayed on the dropdown. After inserting more values in Table category.
On inserting Category C and Category DÂ - Inserting a new Product: We can insert a product C1 in the following manner.
- We get an alert message and the table product gets updated
After submitting the form
Similar Reads
How to define an option in a drop-down list in HTML5 ?
In this article, we will learn how to define an option in a drop-down list in HTML5. The <select> element is used to create a drop-down lists in HTML. This is generally used to present a list of options to the user in a form so that the user could choose one option as the needed one. The <o
2 min read
How to fetch data from the database in PHP ?
Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create, Read, Update and Delete) operations. In this article, we will discuss the Read part i.e. data fetching from database. There are two ways to connect to a database using PHP. They are as follows. MySQLi ("i"
4 min read
How to Add Drop Down List in Table Cell ?
Drop-downs are the user interface elements. Drop Down List is used to select one out of various options. This article focuses on creating a drop down list in the table cell which helps in selecting the choices directly from the table itself. Below are the approaches to add a Drop Down List in a Tabl
3 min read
How to Create a New Database in phpMyAdmin?
We have seen many apps uses any specific backend database or services which are used to store data of the app within itself. In this article we will take a look on creating a new SQL database in phpMyAdmin so that we can perform CRUD operations using that database. In this article we will be simply
3 min read
How to Insert JSON data into MySQL database using PHP?
To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Str
3 min read
How to specify a list of pre-defined options for input controls in HTML?
Specify a list of pre-defined options for input controls by using the HTML list Attribute. A pre-defined option for input controls using HTML5's <datalist> element, allowing users to select from a predefined list while typing in an input field. Syntax: <input list="datalist_id"/>Example
2 min read
How to set the focus on drop-down list automatically when the page loads in HTML5?
The purpose of this article is to focus the drop-down list automatically when the page loads in HTML5. The <select> autofocus attribute is a boolean attribute that specifies that the drop-down list should automatically get focus when the page loads. Syntax: <select autofocus> Example: Th
1 min read
How to Create a Dropdown List with Array Values using JavaScript?
To add elements to the select element from the JavaScript array, We can also get selected values in the dropdown list using JavaScript. Here we will populate the dropdown list with an array.Below are the methods to create a dropdown list with array values:Table of ContentUsing Pure JavaScriptUsing j
2 min read
How to fill all input fields automatically from database by entering input in one textbox using PHP ?
XAMPP is a free and open-source cross-platform web server solution developed by Apache Friends, consisting mainly of the Apache HTTP Server, MySQL database, and interpreter for scripts written in the PHP programming language. The XAMPP server helps to start Apache and MySQL and connect them with the
4 min read
PHP | Inserting into MySQL database
Inserting data into a MySQL database using PHP is a crucial operation for many web applications. This process allows developers to dynamically manage and store data, whether it be user inputs, content management, or other data-driven tasks. In this article, We will learn about How to Inserting into
6 min read