Insert Multi select form into database

How insert multiple values into MySQL from multiple select option

welcome back to shortlearner.com, 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.?

<?php
$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>
<html>
<head>
        <title></title>
</head>
<body>
<form method="post" action="">
<select name="states[]" multiple="multiple">
    <?php 
require("connection.php");
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>
        <?php
    }
    ?>
</select>
<input type="submit" name="Submit"/>
</form>
</body>
</html>

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.

<?php
    if ($_POST) {
require('connection.php');
        $state_string = implode(', ', $_POST['states']);
        $sql = '
            INSERT INTO
                `states` (
                  `name`
                )
            VALUES (
                "'. $state_string .'"
            )';
        mysqli_query($con,$sql);
    }
?>