Tips for updating checkbox values in the database to 1 when selected and 0 when deselected

Managing Database Information

<?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!";


  }
}
?>

Javascript Functionality 

<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>
Checkbox Configuration

<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>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>

Looking to Update Checkbox Values in the Database? Preview of CheckboxesSee jQuery ImplementationSample Database Code Need assistance with this task? Reach out for help as I'm relatively new to this and have been working on it for a week.

Answer №1

It is advisable to refer to the documentation and familiarize yourself with how forms function. There are numerous examples available; I recommend checking out the Head First book series and this link for a good example.

Here is an example code snippet that addresses your issue:

Create a file named example.html and include the following content:


<html>
<head>
<!-- Include jQuery library -->
<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, uncheck if you want to insert</label>
    <input type="checkbox" class="get_value" id='update'/>
    <br>
    <!-- Button for submission -->
    <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 checked values 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>

Create a php file named insert.php with the following code. Ensure both files are in the same directory within your Apache server (localhost public directory):

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

// 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();
?>

You can download the sql file related to the database I used from here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message TypeError: Cannot set property 'randomWord' of undefined specifically at the line: this.randomWord = response.data.word; Confirming that console.log(response.data.word) does display a string. Vue Component Structu ...

The ratio of the length of array to the size of int

In one of my functions, I initialize an array like this: int char_count_array[118] = {0}; Then, I pass this array to another function and perform the following calculations: int xx = sizeof(char_count_array); int xy = sizeof(char_count_array)/sizeof(in ...

Can we condense the code to create a more concise and efficient function?

Can someone help me refactor this code snippet below into a function and combine the two IF statements? Many thanks! let value = productDetails.recentPurchaseDate; if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) { value = false; } ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Error: Does Not Compile When Working With Multi Dimensional Arrays

This program is designed to determine if the sum of elements in the array equals zero. Each row in the multi-dimensional array will include 3 integers, with some potentially being negative based on user input. The program will only execute if integer n m ...

Checkbox selection limitation feature not functioning correctly

Having trouble with my checkbox question function - I want to limit the number of checkboxes that can be checked to 3, but it's still allowing more than that. I suspect the issue lies with latestcheck.checked = false; This is my typescript function: ...

Attempting to maintain the main navigation highlighted while browsing through the secondary navigation

I am facing a small issue that seems like it should be an easy fix, but I can't seem to figure it out. While working on my site, I'm having trouble keeping the parent navigation highlighted when scrolling through the sub-menu. If you hover over ...

What is the correct method to properly encode JSON that may include HTML when displaying it in an HTML file?

After searching through numerous questions, none seem to address this specific scenario. app.get('/', function(req, res) { res.set('Content-Type', 'text/html'); res.send(`<html> <body> Hello, World! </body&g ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

Changes in content result in modifications to the size of transition elements

Have you ever encountered a button with changing text upon being pressed? The transition in text leads to a shift in the button's width. Wouldn't it be amazing if one could smoothly transition the change in width of an element using a code snippe ...

Encountered an error while attempting to load resource in Node.js

I'm currently working on a project utilizing Node js (Express...). Let me do my best to explain the issue I am encountering. My work is being done on localhost, and the main page of my index.html has buttons that lead to other pages when clicked. I c ...

Retrieve items from an array using indexes provided by a separate reference table

I am dealing with two different arrays. One array contains my data: var tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"]; ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Modify the position of the CSS background for the Y-axis using jQuery

Let's consider a scenario with the following table: <table> <tr> <td class="t"></td> <td class="e"></td> <td class="s"></td> <td class="t"></td> </ ...

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Pass an array containing an HTML string to the $.post method in jQuery

I have a problem with displaying HTML content fetched from a PHP script using the jQuery $.post method: $.post('{$site_url}tests/tests/content', params, function (data) { $('#some-div1').html(data[1]); $('#some-div2').htm ...

I'm attempting to retrieve external XML data and showcase it on my HTML page

My goal is to extract any xml tag from the provided sample. However, I am facing an issue with Internet Explorer where I can only retrieve data from the first record. What kind of javascript code should I implement to resolve this problem? <html> ...

Order Varchar Data Array in Ascending Order using PHP

Is there a way to use PHP code to sort an array of varchar data in ascending order? I attempted it myself and the current result is : ABC1 ABC10 ABC11 ABC11A ABC11B ABC2 ABC2A ABC20 ABC3 However, my desired output is : ABC1 ABC2 ABC2A ABC3 ABC10 ABC11 A ...

Adding a loading event listener to an object in JavaScript: A step-by-step guide

I'm currently deep into developing a game using sprites in JavaScript. I've been trying to incorporate an event listener that verifies whether the sprite images have loaded before beginning the game. Employing object-oriented programming, I' ...