How to insert multi drop down using php PDO/MySQL?

Hi there, today I will show How to insert multi drop down using php PDO/MySQL?
Add caption

1.First we need to setup Database.
Lets create the DB called mydb.
add a table called cars. The users table will have the following columns
  1. id
  2. car
CREATE TABLE `cars` (

`id` int(11NOT NULL AUTO_INCREMENT PRIMARY KEY,

`car` varchar(30) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT = 1;

2. Create config.php file for database connection.
<?php
   $servername = "localhost";
   $username = "root";
   $password = "";
   try {
       $conn = new PDO("mysql:host=$servername;dbname=mydb"$username$password);
       $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      
       }
   catch(PDOException $e)
       {
       echo "Connection failed: " . $e->getMessage();
       }
   ?>

3.create form.html and copy paste below code
form.html


<!DOCTYPE html>

<html>

<head>

    <title>Multi select</title>

</head>

<body>

 <form action="submitform.php" enctype="application/x-www-form-urlencoded" id="signup_form" method="POST" accept-charset="utf-8" role="form">

  <select name="cars[]" multiple>

    <option selected>-- Select Cars --</option>

    <option value="volvo">Volvo</option>

    <option value="fiat">Fiat</option>

    <option value="audi">Audi</option>

    <option value="bmw">BMW</option>

    <option value="Jaquar">Jaquar</option>

  </select>

</form> 

</body>

</html>


4. Create submit.php to post above form

<?php

require_once('config.php');

if(isset($_POST['form_submit'])){

    $cars = $_POST['cars'];

    foreach ($cars as $key => $value) {

        $insert_data = $conn->prepare("INSERT INTO cars (car) values ('".$value."')");

        $insert_data->execute();

    }

    if($conn->lastInsertId()>0){

        echo "Data Inserted";

    }

    else{

        echo "Failed to insert";

    }

}

?>


Happy Coding

Comments