我正在尝试检查我的数据库表。
它检查提供的用户名是否存在电子邮件地址或密码。如果它们中的任何一个出现在提供的用户名的数据库中,则会向用户显示错误消息并且不会更改记录。
问题:但是,出于某种原因,我的检查只有在密码和电子邮件都存在的情况下才能生效(如果电子邮件地址为空但密码为空,则不会显示错误消息不)。以下是我的代码:
require ('core/dbcon.php');
$user = mysqli_real_escape_string($con, $_GET['user']);
$acc_status = mysqli_real_escape_string($con, $_GET['status']);
if(empty($_POST['form']) === false){
$usr_email = mysqli_real_escape_string($con, $_POST['email']);
$pwd = mysqli_real_escape_string($con, $_POST['password']);
$rpwd = mysqli_real_escape_string($con, $_POST['rpwd']);
$qry = mysqli_query($con, "SELECT * FROM users WHERE email='$usr_email'") or die(mysqli_error($con));
$usr_details = mysqli_fetch_assoc($qry);
if(empty($usr_details['email'])=== true && empty($usr_details['password'])=== true){
if(mysqli_num_rows($qry) == 0){
if($pwd && $rpwd && $usr_email){
if($pwd === $rpwd){
$pwd = md5($pwd);
$query = mysqli_query($con, "SELECT * FROM users WHERE username='$user' AND email='$usr_email'") or die(mysqli_error($con));
if (mysqli_num_rows($query)== 1){
//update database table
}else{
$errors[] = 'Error! Your details were not added to the system due to a technical error. Please contact the Admin.';
}
}else{
$errors[] = 'Please make sure that the password entered in both fields are the same.';
}
}else{
$errors[] = 'Please complete all fields marked with a red asterisk';
}
}else{
$errors[] = 'Error! <b>'.$usr_email.'</b> already existis in our system.';
}
}else{
$errors[] = 'Error! It looks like the username you have entered has been assigned an email address and password already.';
}
}
我的记录包含用户名&#39; testuser&#39;,email&#39; test@email.com'和密码&#39;密码&#39;。我的检查工作正常,它显示错误&#34;错误!看起来您输入的用户名已经分配了一个电子邮件地址和密码。&#34; 但是,当我从数据库中删除电子邮件地址时,它会以某种方式假设满足以下条件:{{1当if(empty($usr_details['email'])=== true && empty($usr_details['password'])=== true){
时。
我尝试将逻辑运算符从empty($usr_details['password'])===false
更改为&&
,但我遇到了同样的问题(因为OR应该首先接受一个空变量和一个非空变量)。非常感谢您的协助。
答案 0 :(得分:1)
而不是:
if(empty($usr_details['email'])=== true && empty($usr_details['password'])=== true){
试试这个:
if($usr_details['email'] === NULL || $usr_details['password'] === NULL){
对于空数据库值,NULL
更好。
修改强>
您的查询将返回空,因为您只检查$usr_details['email']
,这在数据库中找不到。所以情况会得到满足。
如果您想要正确尝试,请尝试使用username
或unique id
$qry = mysqli_query($con,"select * from user where id=1");
或
$qry = mysqli_query($con,"select * from user where username='username'");
或者您应该在查询中同时检查username
和password
:
$qry = mysqli_query($con,"select * from user where email='email' OR password='password'");
答案 1 :(得分:0)
我刚刚发现问题与Lukas Hajdu暗示的问题有关:
$qry_email = mysqli_query($con, "SELECT email FROM users WHERE email='$usr_email'") or die(mysqli_error($con));
出于某种原因,只有当数据库中已存在电子邮件地址时,才会检查if(empty($usr_details['email'])=== true && empty($usr_details['password'])=== true){
。
要解决此问题,我必须形成另一个查询:
$qry_user = mysqli_query($con, "SELECT * FROM users WHERE username='$user'") or die(mysqli_error($con));
$usr_details = mysqli_fetch_assoc($qry_user);
我不知道为什么会这样,以及如何改进我的代码。所以请随时提供建议:)