我正在嘗試爲使用用戶名和密碼訪問的網站創建用戶區域。我在前端使用HTML,在後端使用JavaScript,在服務器端使用PHP。我使用Xampp來運行本地服務器和PHPMyAdmin來託管數據庫。將空參數發送到PHP的JavaScript
的HTML代碼:
<!-- the Login Section -->
<input type="text" name="userName" placeholder="username" id="usernameBar">
<input type="password" name="passWord" placeholder="password" id="passwordBar">
<button id="loginButton" onclick="Login();">Login</button>
<p id="IncorrectP" title="Incorrect Username or Password" style="display: none">Invalid</p>
的JavaScript:
function Login(){
//Connect to the PHP:
var urlConnect = "checkLogin1.php";
//Get the username and password:
var usrUsername = document.getElementById("usernameBar").value;
var usrPassword = document.getElementById("passwordBar").value;
//Define the parameters to send to php
var strParameters = "usrUsername="+usrUsername + "usrPassword="+usrPassword + "&sid=" + Math.random();
//Define the options for the AJAX request
var objOptions = {
method: "post",
parameters: strParameters,
onSuccess: function(objXHR) {
//If objXHR. responseText = Tenant:
if(objXHR.responseText=='Tenant'){
//Go to tenant space:
alert("Success! (Tenant)");
OpenTenantPage();
}
//Else if objXHR.responseText = Staff:
else if(objXHR.responseText=='Staff'){
//Go to staff space:
alert("Success! (Staff)");
OpenStaffPage();
}
//Else if objXHR.responseText = Admin:
else if(objXHR.responseText=='Admin'){
//Go to admin space:
alert("Success! (Admin)");
OpenAdminPage();
}
else{
//Run IncorrectLogin:
alert("Error! No User Account Found!");
IncorrectLogin();
}
}
}
// define the AJAX request object
var objRequest = new Ajax.Request(urlConnect,objOptions);
}
PHP:
<?php
//Link the username and password:
$connect = mysqli_connect("localhost", "admin", "12345", "realestate") or die ('Connection to database failed: ' . mysql_error());
//Extract variables for request parameters:
extract($_REQUEST);
//Try to log in as a tentant:
$resTenantUser = mysqli_query($connect, "SELECT * FROM tenants WHERE Username='$usrUsername' AND Password='$usrPassword'") or die(mysql_error());
//$resTenantUser = mysqli_query($connect, "SELECT * FROM tenants WHERE Username='Charb1' AND Password='123456' ") or die(mysql_error());
//Set intCount to number of rows in result:
$intCount = mysqli_num_rows($resTenantUser);
if($intCount == 0){
echo "Error!";
}
else{
echo "Tenant";
}
?>
我認爲錯誤我是JS的不發送參數到PHP或它正在發送空的參數。儘管如此我仍然無法找到我的錯誤。
檢查** **開發工具,網絡選項卡中看到什麼實際上是在請求中發送... –
只是爲了改進討論:HTML和JavaScript是你的前端技術(在瀏覽器上運行); PHP是你的後端語言(運行在服務器上) –
**警告**:當使用'mysqli'時,你應該使用[參數化查詢](http://php.net/manual/en/mysqli.quickstart.prepared-statements .php)和['bind_param'](http://php.net/manual/en/mysqli-stmt.bind-param.php)將用戶數據添加到您的查詢中。 **不要**使用字符串插值或連接來完成此操作,因爲您創建了嚴重的[SQL注入漏洞](http://bobby-tables.com/)。 **不要**將'$ _POST','$ _GET'或**任何**用戶數據直接放入查詢中,如果有人試圖利用您的錯誤,這可能會非常有害。 – tadman