簡體   English   中英

如果復選框已選中/未選中PHP,則插入mySQL查詢

[英]Insert mySQL query if checkbox checked/not checked with PHP

在嘗試根據復選框內的值開發一個復選框激活的mySQL查詢的過程中,我遇到了一個我無法解決的問題,此刻我嘗試了以下方法

<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">

函數“ updateStatus”的Javascript / Ajax代碼如下

function updateStatus(id,value) {
if (window.XMLHttpRequest) {
    http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
    http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
    alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
     if (http.readyState == 4) {
        alert(http.responseText);
     }
 }
 http.send(null)

函數/ajax.php中的PHP函數

if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
    $id = mysql_real_escape_string($_GET['id']);
    $checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
    echo "Checked";
} elseif($checked == false) {
    echo "Not checked";
} else {
    echo "Invalid response";
}

使用此代碼時,它總是返回“已檢查”任何主意,為什么?

試試這個(經過代碼測試),

<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">

您將獲得第二個參數為true或false;

function updateStatus(id,checked) {
if (window.XMLHttpRequest) {
    http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
    http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
    alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id+"checked="+checked, true);
http.onreadystatechange = function () {
     if (http.readyState == 4) {
        alert(http.responseText);
     }
 }
 http.send(null)

您的PHP將是:

if(isset($check) and $check == 'update_status' and isset($_GET['id']) AND isset($_GET['checked'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
$query = mysql_query("SELECT * FROM `check_status` WHERE `user_id` = '$_SESSION[userid]' and `id` = '$id'");
else
 //some other query
//Then i can insert the query based on if the checkbox checked or not.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM