如何避免在php中覆盖会话数组

时间:2017-02-02 04:58:11

标签: php jquery checkbox bootstrap-modal

我有一个表单。在文本框下面有一个复选框列表。当我单击每个复选框时,根据来自数据库的复选框,会出现带有子数据的模态。我想要做的是将数据传递到数据库。那已经完成了。但问题是所有子复选框值都没有转到数据库。它只将最后选择的主类别的子类别传递到数据库和其他后期数据。我认为,由于insert.php文件中的会话数组而出现错误。它用新发布的帖子数据覆盖会话变量。(复选框值)。我无法找到它的错误。

我做了一个简单的形式来描述最佳。

的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>

图片1

enter image description here

图片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>";

        }
}


?>

这是我的js文件

$(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');
      }
    }); 

}

当我单击模态上的保存按钮时,选中的复选框值将传递给insert.php文件并存储在会话变量中。

insert.php

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

点击提交按钮后,所有帖子数据都会传递到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);
}


 ?>

我试着向你展示我的想法,希望你能理解。帮助我。

2 个答案:

答案 0 :(得分:1)

最后我解决了自己。

insert.php passData.php 必须修改如下

<强> 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();


 ?>

在此我将数组转换为字符串并将其分配给变量。然后进入会话变量。

答案 1 :(得分:0)

如果你覆盖PHP $ _SESSION超级全局,那么将它复制到另一个对象并使用它;即:

<?php
    if(!empty($_SESSION)){
        $session = array();
        foreach($_SESSION as $key => $data){
            if($key == 'elements_i_dont_want_to_copy'){
                continue;
            }
            // Elements I do want to copy:
            $session[$key] = $data;
        }
    }
    ## Rest of your logic should now use $session, you can manipulate
    ## any elements in $session without destroying any elements of
    ## your $_SESSION.
    ## Pass back what you need from $session to $_SESSION if required
?>