记住数据库中的复选框状态

时间:2018-02-12 21:46:56

标签: javascript php jquery ajax mysqli

我目前有一个简单的复选框,当点击并取消选中时,它会将状态保存到数据库中。刷新页面时,是否可以加载/记住该状态?如果检查了最后一个状态,则在刷新页面后会显示已检查。

我不想使用本地存储空间。我想直接访问数据库。



<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>


<script>
$(document).ready(function(e) {

$("[name='checkboxtest']").change(function(){
    if( $("[name='checkboxtest']").prop('checked') ){checkboxstatus = '1';}
    else{checkboxstatus = '0';}
$.ajax({
        type: "POST",
        url: "checkbox.php",
        data: {checkboxstatus: checkboxstatus},
        })
});//end change
});//end ready
</script>





<?php 
if($row['checkboxstatus'] == 1) { 
    echo "<td><input type = 'checkbox' class='complete' checked='checked' name ='checkboxtest' value= '1'/></td>";
} else {
    echo "<td><input type = 'checkbox' class='incomplete' name ='checkboxtest' value= '0'/></td>";
}
?>
&#13;
&#13;
&#13;

&#13;
&#13;
<?php
$lock = $_POST['checkboxstatus'];

$host = "localhost";
$user = "user";
$password = "password";
$dbname = "dbname";

$conn = mysqli_connect($host,$user,$password,$dbname);
if (mysqli_connect_errno()) {echo "No connection" . mysqli_connect_error();}

$stmt = mysqli_prepare($conn, "UPDATE table
           SET column = ?
           WHERE row = ?");
mysqli_stmt_bind_param($stmt, 'ds', $lock, 'row');
mysqli_stmt_execute($stmt);
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的复选框的nameclass已混淆。

如果您通过$_POST['checkboxstatus']在PHP中访问它,则需要生成name属性checkboxstatus。你还有一些不必要的字符串连接和我在此处删除的=符号周围的额外空格:

if($row['checkboxstatus'] == 1) { 
    echo "<td><input type='checkbox' class='complete' checked='checked' name='checkboxtest' value='1'/></td>";
} else {
    echo "<td><input type='checkbox' class='incomplete' name='checkboxtest' value='0'/></td>";
}

此外,您应该使用mysqli绑定参数。您当前的查询对SQL注入是开放的。

$stmt = mysqli_prepare($conn, "UPDATE table
           SET column = ?
           WHERE row = ?");
mysqli_stmt_bind_param($stmt, 'ds', $lock, 'row');
mysqli_stmt_execute($stmt);