How to update multiple select option in php?

This works perfect for me:

<div class="form-group">
<label for="exampleInputEmail1">Enter Movie Genre [Check for Multiple Select]</label> <br>
<select class="form-control" id="movie_genre"  multiple name="movie_genre[]">
<!-- <option value="choose-category">Choose Movie Genre</option> -->
<?php

$sql = mysqli_query($connection, "SELECT * From genre_info");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)) {
    echo "<option value='".$row['genre_type']
        ."'>".$row['genre_type']
        ."</option>";
}
?>
</select>
</div>

// assigning value

foreach($_POST["movie_genre"] as $row)
{
    $movie_genre.= $row.', ';
}
$movie_genre = substr($movie_genre, 0, -2);

// insert into Db.,

$sql_query1 = "INSERT INTO movies_info (`movie_name`,`movie_image`,`movie_description`,`movie_trailer`,`release_date`,
    `release_year`,`movie_genre`,`movie_rating`,`movie_country`,`is_featured`)
VALUES('$movie_name','$target','$movie_description','$movie_trailer','$release_date',
    '$release_year','$movie_genre','$movie_rating','$movie_country','$is_featured')";

My Question is how to make work for upd

Sometimes its require to quickly modify multiple records and save them to the MySQL database table.

It makes easier to update records instead of updating one by one.

With checkboxes, enable multiple records selected from the list.

In this tutorial, I show how you can update multiple selected records to MySQL with PHP.

How to update multiple select option in php?


Contents

  1. Table structure
  2. Configuration
  3. Record List
  4. Update Records
  5. Output
  6. Conclusion

1. Table structure

Create users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) DEFAULT NULL, 
  `fname` varchar(50) NOT NULL,
  `lname` varchar(50) NOT NULL,
  `age` int(2) DEFAULT NULL,
  `salary` int(10) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Configuration

Create a config.php for database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Record List

Create a <form > which contains submit button for update selected records and <table > to list records.

In the <table > add a checkbox in a <th> for check/uncheck all checkboxes.

Loop on fetched records and create <tr >. In first <td> add the checkbox for record selection. Set name='update[]' and value='<?= $id ?>'.

jQuery Script –

When checkAll checkbox state change then check if it is checked or not. If checked then set all records checkboxes checked property true otherwise false.

On the update checkbox click check if the total number of checkboxes equals to total checked checkboxes. If equal then set checkAll checkbox checked property true otherwise false.

Completed Code

<div class='container'>

  <!-- Form -->
  <form method='post' action=''>

     <!-- Submit button -->
     <input type='submit' value='Update Selected Records' name='but_update'><br><br>

     <!-- Record list -->
     <table border='1' style='border-collapse: collapse;' >
       <tr style='background: whitesmoke;'>
         <!-- Check/Uncheck All-->
         <th><input type='checkbox' id='checkAll' > Check</th>

         <th>Username</th>
         <th>First Name</th>
         <th>Last Name</th>
         <th>Age</th>
         <th>Salary</th>
         <th>Email</th>
       </tr>

       <?php 
       $query = "SELECT * FROM users";
       $result = mysqli_query($con,$query);

       while($row = mysqli_fetch_array($result) ){
         $id = $row['id'];
         $username = $row['username'];
         $fname = $row['fname'];
         $lname = $row['lname'];
         $age = $row['age'];
         $salary = $row['salary'];
         $email = $row['email'];
       ?>
         <tr>

           <!-- Checkbox -->
           <td><input type='checkbox' name='update[]' value='<?= $id ?>' ></td>

           <td><?= $username ?></td>
           <td><input type='text' name='fname_<?= $id ?>' value='<?= $fname ?>' ></td>
           <td><input type='text' name='lname_<?= $id ?>' value='<?= $lname ?>' ></td> 
           <td><input type='number' name='age_<?= $id ?>' value='<?= $age ?>' ></td>
           <td><input type='number' name='salary_<?= $id ?>' value='<?= $salary ?>' ></td>
           <td><input type='text' name='email_<?= $id ?>' value='<?= $email ?>' ></td>

         </tr>
       <?php

       }
       ?>
     </table>
   </form>
</div>

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

  // Check/Uncheck ALl
  $('#checkAll').change(function(){
    if($(this).is(':checked')){
      $('input[name="update[]"]').prop('checked',true);
    }else{
      $('input[name="update[]"]').each(function(){
         $(this).prop('checked',false);
      });
    }
  });

  // Checkbox click
  $('input[name="update[]"]').click(function(){
    var total_checkboxes = $('input[name="update[]"]').length;
    var total_checkboxes_checked = $('input[name="update[]"]:checked').length;

    if(total_checkboxes_checked == total_checkboxes){
       $('#checkAll').prop('checked',true);
    }else{
       $('#checkAll').prop('checked',false);
    }
  });
});
</script>

On <form > submit loop on selected checkboxes ids if selected.

Read the values from DOM elements according to $updateid. If all values entered then execute UPDATE query on $updateid.

Completed Code

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

  if(isset($_POST['update'])){
    foreach($_POST['update'] as $updateid){

      $fname = $_POST['fname_'.$updateid];
      $lname = $_POST['lname_'.$updateid];
      $age = $_POST['age_'.$updateid];
      $salary = $_POST['salary_'.$updateid];
      $email = $_POST['email_'.$updateid];

      if($fname !='' && $lname !='' && $age >0 && $salary >0 && $email != '' ){
         $updateUser = "UPDATE users SET 
                      fname='".$fname."',lname='".$lname."',
                      age=".$age.",salary=".$salary.",email='".$email."' 
                      WHERE id=".$updateid;
         mysqli_query($con,$updateUser);
      }

    }
  }

}

5. Output

View Output


6. Conclusion

For multiple records, selection use checkbox elements and assign record id in the value attribute for accessing it on form submit for select and update records.

You can also use it to delete multiple records.

If you found this tutorial helpful then don't forget to share.

How can I update multiple checkbox values in PHP?

How to Insert Multiple Selected Checkbox Values in Database in PHP.
Step 1: Create a new database and create a new table under it. to create a new Database. Database name is abcd . ... .
Step 2: Create a index. php File. Create an index. ... .
Step 3: Create an update. php File. Create a update..

How set multiple selected values of select box in PHP?

How to get multiple selected values of select box in php?.
For window users – hold down + CTRL key to select multiple option..
For mac users – hold down command key to select multiple option..

How show multiple selected values in dropdown in PHP?

Get Multiple Selected Values of Select Dropdown in PHP Add the multiple tag with select tag also define array with name property. Make sure the Fruits array is not empty, run a foreach loop to iterate over every value of the select dropdown. Display the selected values else show the error message to the user.

How does PHP handle form with multiple selection?

Given a list of items and the task is to retrieve the multiple selected value from a select box using PHP. Use multiple attribute in HTML to select multiple value from drop down list. Selecting multiple values in HTML depends on operating system and browser. Example: This example creates a list of items using HTML.