New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes How insert multiple values into MySQL from multiple select option

How insert multiple values into MySQL from multiple select option

How insert multiple values into MySQL from multiple select option

welcome back to, in the previous post we see how to create a dynamic pie chart with the help of PHP and MySQL. In this post, we will see how to insert data into the MySQL database from multiple select lists using PHP.


Below are the steps to do this :
Firstly we have created a test database and after creating a database created a table state inside it and in the state table, we have stored all the states name in it.

multiselect drop down with checkbox

In the second step we have created a PHP file (connection.php) and in the connection.php file, we have written a database connection code.

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript

Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();

In the index.php page, we fetched all the inserted states from the database and stored all the states in an array.

<!DOCTYPE html>
<form method="post" action="">
<select name="states[]" multiple="multiple">
echo $r="SELECT * FROM tbl_state ;";
    $rr = mysqli_query($con,$r);
    while($row= mysqli_fetch_array($rr))
<option value="<?php echo $row['state_name']; ?>"><?php echo $row['state_name']; ?></option>
<input type="submit" name="Submit"/>

in the action.php page, we used the implode() function which returns a string from the elements of an array. And after that, we have inserted this implode returned selected states into our states table.

    if ($_POST) {
        $state_string = implode(', ', $_POST['states']);
        $sql = '
            INSERT INTO
                `states` (
            VALUES (
                "'. $state_string .'"