我有一个项目的登录信息,我试图弄清楚。我已经通过POST获得了一个值(通过AJAX调用),我已经检查过输入的用户名是否存在并且直到那里,它运行良好。但知道我想检查密码是否对该用户名有效。以下是PHP代码:PHP - MYSQL - 如果用户名存在,请检查特定用户名的密码
<?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 =“登录()”)中形式的按钮,validationLogin()对字段的所有的valitations - >所有工作正常):
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");
}
}
这返回空,我提醒数据只是为了检查一下,有...警报是空的,不明白为什么:/
我试过这个想法 - >PHP mySQL check if username and password are in the database,但在这种情况下,它口口声声说这是不正确的:/
的几个注意事项:
- 我知道密码应该被加密,可能会稍后使用MD5。
- 通过在PHP文件中使用回声和JS文件中的alert(data)/ console.log(data),我只想检查是否有效,以便继续。也许还有其他办法,更好的方式做这一切,我知道,但我喜欢一点一点地去
- 我真的想明白我的代码,然后会改善它,我真的想了解如何以及为什么它的功能或不
- 我想继续使用准备好的语句
感谢大家提前! :)
**从不**存储纯文本密码。你应该使用['password_hash()'](http://us3.php.net/manual/en/function.password-hash.php)和['password_verify()'](http://us3.php。 net/manual/en/function.password-verify.php)。如果您使用的是5.5之前的PHP版本,请不要**使用MD5或SHA1来散列密码。相反,您可以使用[此兼容包](https://github.com/ircmaxell/password_compat)。 –
@AlexHowansky感谢您的支持,在我的帖子结尾处我已经提到了这件事。 – xragdollqueen
*“我试过这个想法 - > PHP mySQL检查用户名和密码是否在数据库中,但在这种情况下,它一直说这是不正确的”* - 我已经在那里接受了答案(可以追溯到2014年) ,所以不管OP的问题代码/答案有什么区别,那么别的东西都会让你失望。 –