samedi 13 février 2021

Checking other checkboxes when clicking on a checkbox and saving them to MySQL

I'm working with MySQL and when you click on the checkboxes, they save their data/value (tinyint(1)) to the database table, so it'll be shown as checkbox either checked or not checked.

Simply said now I want to for examples:

  • When clicking on Advanced that also Intermediate, Basic and Beginner will be checked and saved.
  • When clicking on Basic, only Basic and Beginner will be checked
  • This also means that if for example all are checked (Beginner, Basic, Intermediate and Advanced) and you would uncheck Basic, that both Advanced and Intermediate will unchecked too

I tried some scripts before but if I clicked for example Intermediate, both Basic and Beginner would be checked but when I refreshed the page only Intermediate would have changed. I sadly don't know much about coding to fix this.

Hopefully someone can help me with this.

Down below are some pieces of the code I'm using currently to hopefully give you some idea.

Part of Index.php

echo "<div id=msg_display></div>";

$q="SELECT id,
if( beginner=true,'checked','') as beginner,
if( basic=true,'checked','') as basic,
if( intermediate=true,'checked','') as intermediate,
if( advanced=true,'checked','') as advanced
FROM difficulty limit 0,15";


$i=1;
if ($result_set = mysqli_query($connection,$q)) {
while($row = $result_set->fetch_array(MYSQLI_ASSOC)){
echo "

<input type=checkbox data-column_name='beginner' data-id='$row[id]' $row[beginner]>
<input type=checkbox data-column_name='basic' data-id='$row[id]' $row[basic]>
<input type=checkbox data-column_name='intermediate' data-id='$row[id]' $row[intermediate]>
<input type=checkbox data-column_name='advanced' data-id='$row[id]' $row[advanced]>

";
$i=$i+1;
if(fmod($i,10)==0){//echo $th;
}
}
 $result_set->close();
}

Script inside Index.php

<script>
$(document).ready(function() {
////////////////////    
$('input[type="checkbox"]').change(function(){
var column_name=$(32).data('column_name');
var id=$(this).data('id');
$.post( "data-check.php", {"column_name":$(this).data('column_name'),"id":$(this).data('id')},function(return_data,status){
$("#msg_display").html(return_data);
$("#msg_display").show();
setTimeout(function() { $("#msg_display").fadeOut('slow'); }, 5000);
});
});
//////////////////////////
});
</script>

data-check.php

<?php
$column_name=$_POST['column_name'];
$id=$_POST['id'];
if(!ctype_alpha($column_name)){
echo " Data error ";
exit;
}
include "config-mysqli.php"; // database connection details stored here
$q=" UPDATE difficulty SET $column_name = !$column_name WHERE id=? ";
$stmt = $connection->prepare($q);
if($stmt){
$stmt->bind_param('i',  $id);
$stmt->execute();   
$msg="Data Updated for : $column_name ";    
}else {
$msg="No Data Updated for : $column_name ";     
}
echo "$msg";
?>



Aucun commentaire:

Enregistrer un commentaire