我想将复选框值插入数据库,当我点击特定复选框时必须插入相应的值,但对我来说,先前已复选的复选框值也会再次插入到数据库中,我该如何克服这个问题?
如果我选中复选框1,再次插入数据库,我选中复选框2,我的表显示复选框1,复选框1,复选框2
在这里我使用foreach循环它的问题或任何其他方法来解决这个问题。
JS代码:
$("input[type=checkbox]").on("change", function() {
var ids = [];
var dis = [];
$('input[type=checkbox]:checked').each(function() {
ids.push($(this).val());
});
$('input[type=checkbox]:not(:checked)').each(function() {
dis.push($(this).val());
});
dis = dis.toString();
ids = ids.toString();
$.ajax({
url: "bodcheckbox.php",
type: "POST",
async: true,
cache: false,
data: ({
value: ids,
unchecked: dis,
}),
dataType: "text",
success: function(data) {
alert("activitysubmitted");
}
});
});
PHP代码:
session_start();
include 'config.php';
$username = $_SESSION['username'];
//if(isset($_POST['value']))
//{
//unchecked box value--
$unchecked = $_POST['unchecked'];
$uncheckboxvalue = array();
$uncheckboxvalue = explode(",", $unchecked);
//--checkedbox value--
$checkbox = array();
$checklist = $_POST['value'];
$checkbox = explode(",", $checklist);
$currentdate = date('d-m-Y');
$year = date('Y', strtotime($currentdate));
$month = date('F', strtotime($currentdate));
$date = date('d', strtotime($currentdate));
date_default_timezone_set('Asia/Kolkata');
$currenttime = date("h-i-sa");
if (!empty($checklist)) {
foreach ($checkbox as $check) {
$bod_insert = mysql_query("insert into bod(username,activityname,tickeddate,tickedtime,status)values('$username','" . mysql_real_escape_string($check) . "','$date-$month-$year','$currenttime','yes')", $conn);
}
foreach ($uncheckboxvalue as $uncheck) {
$bod_update = mysql_query("update bod set status='no' where activityname='" . mysql_real_escape_string($uncheck) . "' and username='$username'", $conn);
}
}
答案 0 :(得分:0)
您可以尝试这样的方法来获取当前已检查元素的当前状态:
$("input[type=checkbox]").on("change", function() {
var ids = null;//set to null for unchecked
if (this.checked) {//set the value for checked
var ids =$(this).val();
}
$.ajax({
url: "bodcheckbox.php",
type: "POST",
async: true,
cache: false,
data: ({
value: ids,
}),
dataType: "text",
success: function(data) {
alert("activitysubmitted");
}
});
});
答案 1 :(得分:0)
您需要通过查询表是否具有相同活动和相同用户名的记录来进行检查。获取结果计数,如果为0,则插入记录,否则无变化