首页 > 解决方案 > How to update values of checkbox to the database 1 if checked and 0 if unchecked?

问题描述

This is my database

<?php
if(isset($_POST["insert"]))
{
   $conn = mysqli_connect("localhost", "root", "", "databaseappfeature");

   if(isset($_POST["insert"]) == "1"){
   $query = "UPDATE appfeature SET feature_switch = ('".$_POST["insert"]."')";
   $result = mysqli_query($conn, $query);
   echo "Data Inserted Successfully!";


  }
}
?>

This is my javascript code

<script>
  $(document).ready(function(){
     $('#submit').click(function(){
       var insert = [];

       $('.get_value').each(function(){
         if($(this).is(":checked"))
         {
         insert.push($(this).val());
         }
       });

       insert = insert.toString();

       $.ajax({
       url: "insert.php",
       method: "POST",
       data:{insert:insert},
       success:function(data){
       $('#result').html(data);
       }
       });
     });
  });
</script>
This is my checkbox code

<form action="" method="POST">

<h4 id="result"></h4>

<div class="container">
  <h2 align="center">Table App Feature</h2>   
        
  <table id="appFeature" class="table table-hover" align="center" style="width:500px;margin:auto;">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Please check to enable the features</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Smarthome</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Intercom</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>

       <tr>
        <td>Visitors</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Booking</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Access</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Parcel</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Bills</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Invoices</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      <tr>
        <td>Receipts</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Transactions</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Meeting</td>
        <td>
          <input type="checkbox" class="get_value" value="1"  />
        </td>
      </tr>
      <tr>
        <td>Vote</td>
        <td>
          <input type="checkbox" class="get_value" value="1"/>
        </td>
      </tr>
      <tr>
        <td>Feedback</td>
        <td>
          <input type="checkbox" class="get_value" value="1" />
        </td>
      </tr> 
    </tbody>
  </table><br />
  <div align="center">
    <button type="button" name="submit" id="submit">Update</button>
  </div>
</div>
</form>

How can i update the value of multiple checkbox into the database and the value should be 1 if the checkbox is checked and 0 if the checkbox is unchecked?? This is my checkboxThis is jquery that i use to pass the value of checkboxThis is my database code Please help me..i'm very new to this..and i'm doing this for a week..

标签: javascriptarraysdatabasecheckbox

解决方案


Please go though documentation and understand the way how the forms works. There are plenty of examples out there I would recommend Head First book series and here you can find a good example.

And also here is the example code for your problem

create a file named example.html and save this content

    <html>
    <head>
<!-- link to jquery lib -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
    <form action="" method="POST">

    <h4 id="result"></h4>

    <div class="container">
      <h2 align="center">Table App Feature</h2>   
            <label> Name </label>
        <input type='text' name='name' id='name' value=''/>
      <table id="appFeature" class="table table-hover" align="center" style="width:500px;margin:auto;">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Please check to enable the features</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Smarthome</td>
            <td>
<!-- checkbox for smarthome value -->
              <input type="checkbox" class="get_value" id='smarthome'/>
            </td>
          </tr>
        <tr>
            <td>Intercom</td>
            <td>
              <input type="checkbox" class="get_value" id='intercom'/>
            </td>
          </tr>
        </tbody>
      </table><br />
      <div align="center">
        <label>check if you want to update, unckeck if you want to insert</label>
        <input type="checkbox" class="get_value" id='update'/>
        <br>
<!-- button name -->
            <button type="button" name="submit" id="submit">Update or Insert</button>
      </div>
    </div>
    </form>
    </body>
    <script type="text/javascript">
      $(document).ready(function(){
         $('#submit').click(function(){
// get the value is checked from the form
           $.ajax({
           url: "insert.php",
           method: "POST",
           data:{intercom: $('#intercom').is(':checked'),smarthome: $('#smarthome').is(':checked'), name: $('#name').val(), update: $('#update').is(':checked')},
           success:function(data){
           $('#result').html(data);
           }
           });
         });
      });
    </script>
    </html>

php file as follows named insert.php . make sure both files are in the same directory and inside your apache server.(localhost public directory)

<?php
$servername = "localhost";
$username = "YOURDBUSER";
$password = "YOURDBPASSWORD";
$dbname = "databaseappfeature"; // db name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql ;

if($_POST['update']){
    $sql = "UPDATE appfeature SET smarthome=".$_POST['smarthome'].", intercom=".$_POST['intercom']." WHERE name='".$_POST['name']."'";
}else{
    $sql = "INSERT INTO appfeature (name, smarthome, intercom) VALUES ('".$_POST['name']."',".$_POST['smarthome'].",".$_POST['intercom'].")";
}

if ($conn->query($sql) === TRUE && !$_POST['update']) {
    echo "New record created successfully";
}else if($conn->query($sql) === TRUE && $_POST['update']){
    echo "record updated";
}else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

here is the sql file related to the database i used


推荐阅读