Dynamic checkbox with PHP and MySQL On & Off

Monday 15 July 2019

Sample HTML/PHP Form:

<?php
include('config.php');
?>

<!DOCTYPE html>
<html>
<body>

<form method="post" action="" enctype="multipart/form-data">
<?php
$sql=mysqli_query($conn,"SELECT * FROM cruds");
   
echo "<table border='1'><tr>";
$i = 0;
while( $rs=mysqli_fetch_array($sql) ) {
    echo "<td><input type='checkbox' name='bike_id[]' class='names' value='".$rs['id']."'> </td>";
    $i++;
    if($i%4==0){
        echo "</tr><tr>";
    }
}
echo "</tr></table>";     
?>
    <br>
  <input type="submit"  name="Submit">
</form>
</body>
</html>

PHP Code:

<?php
if(isset($_POST['bike_id'])){
       $invite = implode("','",$_POST['bike_id']);
        $final_id="'".$invite."'";
    echo "update cruds set status='1' where id in($final_id)";
      mysqli_query($conn,"update cruds set status='1' where id in($final_id)"); // to update 1 for checked checkbox
      mysqli_query($conn,"update cruds set status='0' where id not in($final_id)"); // to update 0 for unchecked checkbox
    }
?>
 

Blogger news

Blogroll

Most Reading