如何使用AJAX执行MYSQLI查询(预处理语句)

时间:2014-04-29 22:38:25

标签: php jquery ajax mysqli

所以我在PHP(部分代码)中有这个(预备语句)mysqli查询:

#New DB connection
@ $mysqli = new mysqli ('localhost', 'user', 'password', 'database');

#Check DB connection, print error upon failure
if (mysqli_connect_errno()) {
    printf("<p>Connect failed.</p> <p>Error: \"%s\"</p>\n", mysqli_connect_error());
    exit();
} #if

#Check if userName already exists
$query = "SELECT * FROM users WHERE userName = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $registerUserName);
$stmt->execute();
$stmt->store_result();
$num_results = $stmt->num_rows;
if ($num_results) {
    echo "<p>This user already exists. Please click your back button.</p>";
    exit;
}; #if

我想在onblur事件中通过Javascript / AJAX执行此操作:

function checkForUser(str) {
  var xmlhttp;    
  if (str=="") {
    return;
  }
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open(???,true); // not sure what goes here or if I should even use this method
  xmlhttp.send();
}

这可能吗?如何?我找到了一些教程,但它们涉及使用jquery。我可以不用jquery吗?

1 个答案:

答案 0 :(得分:0)

我改变了你的代码。希望它会有所帮助:

#New DB connection
@ $mysqli = new mysqli ('localhost', '…', '…', '…');

#Check DB connection, print error upon failure
if (mysqli_connect_errno()) {
    printf("<p>Connect failed.</p> <p>Error: \"%s\"</p>\n", mysqli_connect_error());
    exit();
} #if

#Check if userName already exists
$query = "SELECT * FROM wp_users WHERE user_login = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $_GET[registerUserName]); 
$stmt->execute();
$stmt->store_result();
$num_results = $stmt->num_rows;
if ($num_results) {
    echo "<p>This user already exists. Please click your back button.</p>";
    exit;
}; #if

现在我们可以使用&#34; /ttt.php这样的URL来调用它?registerUserName = user1&#34; 功能:

function checkForUser(uname)
{
var req;
req = null;
if (window.XMLHttpRequest) {
    try {
        req = new XMLHttpRequest();
    } catch (e){}
} else if (window.ActiveXObject) {
    try {
        req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e){
        try {
            req = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e){}
    }
}

if (req) {       
    req.open("GET", "/ttt.php?registerUserName="+encodeURIComponent(uname), false);
    //req.onreadystatechange = processReqChange;
    req.send(null);
    if(req.status == 200) {
      return req.responseText;
    }

}
return false;
}

中的

req.open("GET", "/ttt.php?registerUserName="+encodeURIComponent(uname), false);

false 表示异步请求, req.send 将等待来自php脚本的响应。