I have this code and I want to add checkbox according to fetched number from database with PHP and when clicked on checkbox update a field in db with JQuery, this work for 1 checkbox but this cant work for more checkbox and Also my PHP loop does not work how i can add checkbox with loops and when user click on any checkbox update His own field on database, anybody can resolve my problem ?
My JQuery code:
$(document).ready(function () {
$('#mycheckbox').change(function () {
var returnVal = ("Are " + "you sure?");
if (returnVal) {
postToServer($(this).prop("checked"));
} else {
$(this).prop("checked", !$(this).is(":checked"));
}
});
function postToServer(state) {
let value = (state) ? 1 : 0;
$.ajax({
type: 'POST',
url: 'checkbox.php',
data: {'value': +value},
success: function (response) {
//handle response
}
});
}
}
and my PHP code:
$sql1="SELECT * FROM `users` ";
$result1= mysqli_query($conn,$sql1);
$row1=mysqli_fetch_assoc($result1);
$lights=$row1["lights"];
for ($i=0; $i < $lights; $i++){
if ($row["value"]=='1'){
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" checked=\"checked\">";
} else {
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" >";
}
}