2017-04-24 17 views
0

我想插入複選框的值到數據庫中,當我點擊特定的複選框相應的值必須插入但我以前檢查複選框的值也再次插入到數據庫我怎麼能克服這個?
如果我選中了複選框1,再次插入數據庫我選中了複選框2,我的表格顯示了checkbox1,checkbox1,checkbox2。
這裏我用foreach循環它的問題或任何其他方法是否有這個問題。如何插入複選框的值,而不使用數組在jquery

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

你只想插入當前所選元素的值? – madalinivascu

+0

是madalin只有當前複選框的值 – arjun

回答

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"); 
    } 
    }); 
}); 
+0

感謝madalin如果再次複選框未選中意味着我必須更新狀態爲='不' – arjun

+0

是在服務器端你做一個如果測試如果該值爲空或一個數字和基礎在那你更新你的狀態 – madalinivascu

0

您需要通過查詢表格是否具有相同活動和相同用戶名的記錄進行檢查。獲得結果的計數,如果是0,則插入記錄,否則不變

相關問題