我已经登录了一个我想弄清楚的项目。我通过POST获得了一个值(通过AJAX调用),我已经检查过输入的用户名是否存在并且在那里,它运行良好。但是知道我想检查密码是否对该用户名有效。这是PHP代码:
<?php
//File with the conection data
include_once "../conexion.php";
//Initialization
$user = "";
$password = "";
$errors = "";
$result = "";
$result2 = "";
//Some validations (I've edited a little to make it shorter)
if((isset($_POST['user'])) && (!empty($_POST['user']))){
$user = $_POST['user'];
}else{
$errors .= "blablablah";
}
if((isset($_POST['password'])) && (!empty($_POST['password']))){
$password = $_POST['password'];
}else{
$errors .= "blablabla";
}
//I make the query
$sql = "SELECT user FROM users WHERE user = ?";
//I prepare the query
if($stmt = $con->prepare($sql)){
$stmt->bind_param('s', $user);
$result = $stmt->execute();
}
/* UP TO HERE, if I check that $result is true and echo "User exists" or something like that, IT WORKS, AS THE USER EXISTS */
/* BUT now I want to check the PASSWORD, given that the user exists */
if($result){
//I make the query
$sql2 = "SELECT user, password FROM users WHERE user = ? AND password = ?";
//I prepare the query
if($stmt2 = $con->prepare($sql2)){
$stmt2->bind_param('ss', $user, $password);
$result2 = $stmt2->execute();
if($result2){
echo "ENTERED";
}else{
echo "PASSWORD OR USER INCORRECT";
}
}
}
?>
我在AJAX调用的成功函数中使用了那些回声的结果,这里是代码(有一个onClick事件(onClick =&#34; login( )&#34;)在表单的按钮中,validationLogin()具有字段的所有valitation - &gt;所有工作正常):
function login(){
if(validationLogin()){
$.ajax({
url: "http://localhost/myProject/extras/Login.php",
type: "POST",
data: {"user": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
alert(data);
console.log(data);
}
});
}else{
//alert("Incorrect fields");
}
}
这会返回EMPTY,我会提醒数据只是检查它有什么...警报是空的,不明白为什么:/
我已尝试过这个想法 - &gt; PHP mySQL check if username and password are in the database但在这种情况下,它一直说不正确:/
一些注意事项:
提前感谢大家! :)
答案 0 :(得分:2)
你应该试试这个:
$sql = "SELECT user,password FROM users WHERE user = ?";
//I prepare the query
if($stmt = $con->prepare($sql)){
$stmt->bind_param('s', $user);
$result = $stmt->execute();
if ($result) {
$stmt->bind_result($user_name,$password_db);
} else {
$user_name="";
$password_db="";
}
// Check Password
if ($password==$password_db){
/// PASSWORD IS OK
}
}
现在,您拥有$ user_name中的用户和$ password中的密码(如果存在),因此您不需要第二个sql语句。在PHP函数中,您可以使用:
data: {"user": <?php echo $user_name ?>,
"password": <?php echo $password_db ?> ,
},