我有一个小脚本,它从我的客户端获取用户名和密码,如果他们的凭据正确,他们就会被带到我的开发服务器上的站点目录中。
if
条件运行良好,并响应与MySQL数据库中计数器部分匹配的正确凭据。
但是,else
条件根本不会执行(即,如果用户的凭据不正确,它不会将用户引导到错误页面)。我认为while
循环可能会触发逻辑,但我需要$row
变量来从DB中获取目录字段。
有什么想法吗?
$username = stripslashes($_POST['username']);
$password = stripslashes($_POST['password']);
$pass = md5($password);
$conn = mysqli_connect("localhost", "root", "", "digital_server");
$sql = "SELECT * FROM projects WHERE username = '$username' AND password = '$pass'";
$query = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($query)) {
if($query) {
header("Location: " . $row['directory'] . "/");
}
else {
header("Location: http://dev.myserver.com/error.php");
}
}
已解决非常感谢所有提供帮助的人。
修改后的代码块删除while并创建一个$row
变量以获得if
逻辑所需的数据
$row = mysqli_fetch_assoc($query);
if(mysqli_num_rows($query) > 0) {
header("Location: " . $row['directory'] . "/");
}
else {
header("Location: http://dev.myserver.com/error.php");
}
// No need of while here
//while() {
if( mysqli_num_rows($query) > 0 ) {
$row = mysqli_fetch_assoc($query);
header("Location: " . $row['directory'] . "/");
} else {
header("Location: http://dev.myserver.com/error.php");
}
选项2
$sql = "SELECT * FROM projects WHERE username = '$username' AND password = '$pass'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
if(count($row ) > 0 ) {
header("Location: " . $row['directory'] . "/");
} else {
header("Location: http://dev.myserver.com/error.php");
}
您可能正在寻找mysqli_num_rows($result);
$query = mysqli_query($conn, $sql);
if( mysqli_num_rows($query) > 0 ) {
$row = mysqli_fetch_assoc($query);
header("Location: " . $row['directory'] . "/");
}else{
header("Location: http://dev.myserver.com/error.php");
}
您总是可以使用捕获查询中的错误mysqli_error
$username = stripslashes($_POST['username']);
$password = stripslashes($_POST['password']);
$pass = md5($password);
$conn = mysqli_connect("localhost", "root", "", "digital_server");
$sql = "SELECT * FROM `projects` WHERE `username` = '$username' AND `password` = '$pass'";
$query = mysqli_query($conn, $sql);
if( mysqli_num_rows($query) > 0 ) {
$row = mysqli_fetch_assoc($query);
header("Location: " . $row['directory'] . "/");
}
else
{
header("Location: http://dev.myserver.com/error.php");
}