phpjquerycheckboxbootstrap-modal

how to avoid overwriting of session array in php


I have a form. In which there is a group of checkboxes. When I click on each checkbox, a modal appears with sub data which is coming from the database based on the particular checkbox.

What I want to do is to pass data into the database. That is already done. However, the issue is that all the values from the sub-checkboxes are not being saved to the database. Only the subcategories of the last selected main category, along with other post data, are being saved into the database.

I believe the issue lies within the insert.php file, specifically with the session array. It appears that the session variable is being overwritten with the new POST data (checkbox values), which is causing the problem. I haven't been able to determine exactly what is wrong.

I made a simple form to describe best.

config.php

<?php
   $servername = "localhost";
   $username = "root";
   $password = "";
   $db = "mydb";

 // Create connection
    $conn = mysqli_connect($servername, $username, $password,$db);

// Check connection
   if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
      }
?>  

form.php

<body>
<div class="form1">
<form action="passData.php" method="post">

    <input type="text" name="name" placeholder="Name"/><br>
    <input type="text" name="age" placeholder="age"/><br>
    <input type="text" name="address" placeholder="address"/><br>
    <input type="checkbox" name="favourite" value="1"/>sports
    <input type="checkbox" name="favourite" value="2"/>fruits
    <input type="checkbox" name="favourite" value="3"/>colors
    <div>
        <button class="btn btn-primary" type="submit" name="submit" id="submit">Submit</button>
    </div>
</form>    
</div>

     <!--modal-->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
       
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary btn-fill" id="submit" onclick="submit();" name="submit" >save</button>

      </div>
    </div>
  </div>
</div><!--modal is finished-->

                                
</body>

Image 1

enter image description here

Image 2

enter image description here

modal.php

<?php   
   if($_POST['value']){
      $value = $_POST['value'];
      include("config.php");

      $sql = "SELECT sub_categories FROM favourite WHERE category_id=".$value." ";
      $res = mysqli_query($conn,$sql);
      while($row = mysqli_fetch_array($res)){
      echo "<input class='category' type='checkbox' name='category[]' value ='".$row['sub_categories']."'/>".$row['sub_categories'];
      echo "<br>";

        }
}


?>

Here is my JS file

$(document).ready(function(){
    //model 
    $("input[type=checkbox][name=favourite]").on('change',function(){
     if(this.checked) {
             
        var value = $(this).val();
        $.ajax({
            url:"modal.php",
            type:"POST",
            data:{value:value},
            success:function(modalBody){
                $("#myModal .modal-body").html(modalBody);
                $("#myModal").modal('show');
             
            }

        });
    }
       });
});



 function submit() {
   
     var insert = [];
     $('.category:checked').each(function(){
           insert.push($(this).val()); 
        });
     
     insert = insert.toString();
            $.ajax({
            url:'insert.php',
            type:'POST',
            data:{insert:insert},
            success:function(){
             alert('success');
             $("#myModal").modal('hide');
      }
    }); 

}

When I click the save button on the modal, the selected checkbox values are passed to the insert.php file and stored in a session variable.

insert.php

<?php
if (!isset($_SESSION['insert'])) {
$_SESSION['insert'] =[];
 }
$insert = $_POST['insert'];
array_push($_SESSION['insert'], $insert);
?>

After click on submit button all post data are passed to passData.php

passData.php

<?php
session_start();

include('config.php');

if(isset($_POST['submit'])){
   $name=$_POST['name'];
   $age=$_POST['age'];
   $address=$_POST['address'];
   
$sql= "INSERT INTO students(name,age,address,favourite) VALUES('$name',
       '$age',
       '$address',
       '".$_SESSION['insert']."');" ;
$result=mysqli_query($conn,$sql);
}


 ?>

I'm trying to convey my idea to you and hope you can understand it. Please help me.


Solution

  • Finally I solved it by myself.

    insert.php and passData.php must be modified as follows.

    insert.php

    <?php
    session_start();
    
        if (!isset($_SESSION['insert'])) {
        $_SESSION['insert'] = array();
        }
        $insert = $_POST['insert'];
        array_push($_SESSION['insert'], $insert);
    
        $list = implode(",", array_filter($_SESSION['insert']));
    
        $_SESSION['final'] = $list;
    
    ?>
    

    passData.php

    <?php
    session_start();
    
    include('config.php');
    
    if(isset($_POST['submit'])){
       $name=$_POST['name'];
       $age=$_POST['age'];
       $address=$_POST['address'];
       
    
    
           $sql= "INSERT INTO students(name,age,address,favourite) 
       VALUES('$name',
              '$age',
              '$address',
              '".$_SESSION['final']."');" ;
       $result=mysqli_query($conn,$sql);
    
       }
    
    unset($_SESSION['final']);
    session_destroy();
    
    
     ?>
    

    In this process, I convert an array into a string, assign it to a variable, and then store it in a session variable.