简体   繁体   中英

update database with checkbox

My database table has 2 fields: id (int) and state (enum -> 0,1).

What I need to do is to update my database (my state field) with the state of a checkbox ( 0 for empty, 1 for checked).

To show each of the fields in my database, I use a loop:

Loop:

<?php
foreach ( $posts_array as $module )
{
?>
    <h2><?php echo $module->titre; ?></h2>
    <input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>

My update file:

foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
    // $_GET['onoffswitch-checkbox'] = class for all my checkboxed
    // $id = my database row id
    // $state = on/off
    $query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
    $id++;
}

Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:

AJAX

$(document).ready(function() {
    $("onoffswitch-checkbox").click(function() {
        var id = $(this).attr('id');
        $("#state_span").load("module_update.php?"+id); 
    }
}

I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.

Try this:

AJAX

$(document).ready(function() {
    $(".onoffswitch-checkbox").click(function() {
        var id = this.id;  //changed here also, just because jQuery is not needed here
        var state = this.checked ? 1 : 0;
        $("#state_span").load("module_update.php?id="+id+"&state="+state); 
    }
}

Changed 3 things:

  • added a dot in $("onoffswitch-checkbox") so its now $(".onoffswitch-checkbox")
  • added id= after module_update.php? and before id value.
  • since you need state also I added that also with a & to separate the values for $_GET in php to separate them

PHP

I don't know what you mean with $_GET['onoffswitch-checkbox'] in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.

Since you will be only clicking one at a time I see no need for the foreach loop in php, so you could do this:

$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM