简体   繁体   中英

Save multiple row of checkbox value into database

I am creating a form that involves checkboxes. There is 5 checkboxes in a row. If the user adds another row, there will be another 5 checkboxes.

It looks like this, 在此处输入图片说明

The code i used,

 <tbody id="dataTable"> <tr> <td> <input type="text" class="form-control" name="startTime[]"> </td> <td> <input type="text" class="form-control" name="endTime[]"> </td> <td> <input type="checkbox" name="Monday[0]" value="1"> </td> <td> <input type="checkbox" name="Tuesday[0]" value="1"> </td> <td> <input type="checkbox" name="Wednesday[0]" value="1"> </td> <td> <input type="checkbox" name="Thursday[0]" value="1"> </td> <td> <input type="checkbox" name="Friday[0]" value="1"> </td> <td> <input type="button" class="btn btn-danger" value="Delete" onClick="deleteRow('dataTable')" /> </td> </tr> </tbody> 

The code that i use for inserting the data to the database,

 <?php if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } else { if ($_POST['startTime']) { foreach ($_POST["startTime"] as $key => $value) { $endTime = $_POST["endTime"][$key]; $monday = isset($_POST["Monday"][$key]) ? 1 : 0; $tuesday = isset($_POST["Tuesday"][$key]) ? 1 : 0; $wednesday = isset($_POST["Wednesday"][$key]) ? 1 : 0; $thursday = isset($_POST["Thursday"][$key]) ? 1 : 0; $friday = isset($_POST["Friday"][$key]) ? 1 : 0; $sql = "INSERT INTO timetableschedule ( startTime, endTime, Monday, Tuesday, Wednesday, Thursday, Friday) " . "VALUES ('$value', '$endTime', '$monday', '$tuesday', '$wednesday', '$thursday', '$friday')"; mysqli_query($con, $sql); } } echo "1 record added"; mysqli_close($con); } ?> 

Suppose i submit the form the way i showed in the above image, i gotten this result in the database, 在此处输入图片说明

The value that suppose to be with the time "1600 1700" appeared on the "1400 1500" row. I would want the values to be saved accordingly as selected.

EDIT : removing the zeros ( name="Monday[]" ) will not solve the problem because unchecked radio or checkbox elements are not submitted.

I would consider adding an index to your checkbox names while generating the rows, like:

  <input type="checkbox" name="Monday[0]" value="1">

  <input type="checkbox" name="Tuesday[0]" value="1">

...

  <input type="checkbox" name="Monday[1]" value="1">

  <input type="checkbox" name="Tuesday[1]" value="1">

...

  <input type="checkbox" name="Monday[2]" value="1">

  <input type="checkbox" name="Tuesday[2]" value="1">

This way your PHP loop should work

The JSON way:

 function sendFunction() { //tr var checkboxJSON = {}; var i = 0; var tr = $("#dataTable > tr").each(function(){ //checkboxes checkboxJSON[i] = {}; $(this).find("input[type='checkbox']").each(function(){ if ($(this).is(':checked')) { checkboxJSON[i][$(this).attr("name")] = 1; } else { checkboxJSON[i][$(this).attr("name")] = 0; } }); i++; }); var checkboxData = JSON.stringify(checkboxJSON); //send this to the server as checkboxdata! console.log(checkboxData); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody id="dataTable"> <tr> <td> <input type="text" class="form-control" name="startTime[]"> </td> <td> <input type="text" class="form-control" name="endTime[]"> </td> <td> <input type="checkbox" name="Monday" value="1"> </td> <td> <input type="checkbox" name="Tuesday" value="1"> </td> <td> <input type="checkbox" name="Wednesday" value="1"> </td> <td> <input type="checkbox" name="Thursday" value="1"> </td> <td> <input type="checkbox" name="Friday" value="1"> </td> <td> <input type="button" class="btn btn-danger" value="Delete" onClick="deleteRow('dataTable')" /> </td> </tr> <tr> <td> <input type="text" class="form-control" name="startTime[]"> </td> <td> <input type="text" class="form-control" name="endTime[]"> </td> <td> <input type="checkbox" name="Monday" value="1"> </td> <td> <input type="checkbox" name="Tuesday" value="1"> </td> <td> <input type="checkbox" name="Wednesday" value="1"> </td> <td> <input type="checkbox" name="Thursday" value="1"> </td> <td> <input type="checkbox" name="Friday" value="1"> </td> <td> <input type="button" class="btn btn-danger" value="Delete" onClick="deleteRow('dataTable')" /> </td> </tr> </tbody> </table> <input type="button" class="btn btn-danger" value="Send" onClick="sendFunction('dataTable')" /> 


For your solution. to work:

  1. Set a hidden input to your form.
 <input type="hidden" value="{}" name="checkboxes" />
  1. Use an onSubmit event on your form
 <form id="formDates" action="file.php" method="post" onSubmit="checkForm" />   
  1. Write the submit function with the checkbox code:
 function checkForm(e)
 {
     e.preventDefault(); //prevents form from being sent to early

     var checkboxJSON = {};
     var i = 0;
     var tr = $("#dataTable > tr").each(function(){
         //checkboxes
         checkboxJSON[i] = {};
         $(this).find("input[type='checkbox']").each(function(){

            if ($(this).is(':checked'))
            {
              checkboxJSON[i][$(this).attr("name")] = 1;
            }
            else
            {  
                checkboxJSON[i][$(this).attr("name")] = 0;
            }
         });
         i++;
      });

      $("input[type='hidden']").val(JSON.stringify(checkboxJSON)); //save this to the hidden input.
     document.getElementById("formDates").submit(); //submit all the data.
 }
  1. In PHP you can rebuild this data into an array with json_decode()
$checkboxes = json_decode($_POST['checkboxes'], true); //use true to set it as an array.
foreach ($_POST["startTime"] as $key => $value) {

        $endTime = $_POST["endTime"][$key];
        $monday = $checkboxes[$key]['Monday']; //key should refer to an INT. 0 for the first row.
        $tuesday = $checkboxes[$key]['Tuesday'];
        $wednesday = $checkboxes[$key]['Wednesday'];
        $thursday = $checkboxes[$key]['Thursday'];
        $friday = $checkboxes[$key]['Friday'];


        $sql = "INSERT INTO timetableschedule ( startTime, endTime, Monday, Tuesday, Wednesday, Thursday, Friday) " .
                "VALUES ('$value', '$endTime', '$monday', '$tuesday', '$wednesday', '$thursday', '$friday')";
        mysqli_query($con, $sql);
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM