首页 > 解决方案 > insert multiple checkbox value using jquery and ajax but i only insert one record

问题描述

I have this table in my database,

see table image

Now, in the raw_selected_rubric(Level) column that is where I will insert multiple values based on how many checkbox have been check. For example,

checkbox image

Based on the picture I have selected the level 3 and level 4 and when I click submit only the level 3 value is inserted on my database.

inserted checkbox

Input field,

<input class="rubricChkbox" type="checkbox" value="3" />

Jquery and Ajax,

var rubricChkbox = [];
    $('.rubricChkbox').each(function(){  
            if($(this).is(":checked"))  
            {  
                 rubricChkbox.push($(this).val());  
            }  
       });  
       rubricChkbox = rubricChkbox.toString();
$.ajax({
        url: "Queries/save.php",
        type: "POST",
        data: { 
              "rubricChkbox":rubricChkbox
              },
        success: function(yey){
          console.log(yey);
          alert(yey);
        }
      });

Queries/save.php,

if(isset($_POST['rubricChkbox'])) {
$rubric_value = $_POST['rubricChkbox'];

        $sql_raw = "INSERT INTO rubric_selected (raw_selected_rubric, Saved, ID_cmat, ID_users)

        VALUES  ('$rubric_value', '1')";

        $success = mysqli_query($conn, $sql_raw); 
}

What's wrong in my code? I'm sorry I'm still learning jquery and ajax. Thank you for the help.

What I want to happen is that if I selected Level 3 and 4 it both data will be inserted like this,

expected output

标签: phpjquerymysqlajax

解决方案


您需要有多个这样的插入语句,例如:

if(isset($_POST['rubricChkbox'])) {
$rubric_value = $_POST['rubricChkbox'];
    foreach($rubric_value as $value){
           $sql_raw = "INSERT INTO rubric_selected (raw_selected_rubric, Saved, ID_cmat, ID_users)

            VALUES  ('$value', '1')";

            $success = mysqli_query($conn, $sql_raw);

    }
}

推荐阅读