【发布时间】:2020-01-01 01:59:55
【问题描述】:
我制作了一个登录表单。该表单有效,并且在用户输入正确的电子邮件和密码后,授予访问权限。有一个问题。 我使用一个 foreach 循环来测试所有结果(应该是一个帐户)。
foreach ($result as $outp) {
$role = $outp->role;
$name= $outp->name;
$surname= $outp->surname;
$_SESSION["name"] = $name;
$_SESSION["surname"] = $surname;
$_SESSION["role"] = $role;
if($_SESSION["role"] == 'Admin') {
header("location:index.php");
} else
if($_SESSION["role"] == 'User') {
header("location:../index.php");
} else {
header("location:login.php");
}
}
此代码应该检查帐户角色,并确定它可以转到哪个页面。 问题是 foreach 循环内的所有内容都没有被执行。
在这里您可以看到完整的代码,包括 foreach 循环(仅 php):
if(isset($_POST["login"]))
{
if(empty($_POST["email"]) || empty($_POST["password"]))
{
$message = '<label>Some fields are still empty</label>';
}
else
{
$query = "SELECT * FROM account WHERE email = :email AND password= :password";
$statement = $con->prepare($query);
$statement->execute(
array(
'email' => htmlspecialchars($_POST["email"]),
'password' => htmlspecialchars($_POST["password"])
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["email"] = $_POST["password"];
$username = $_SESSION["email"];
$query = "SELECT role, name, surname FROM account WHERE email = :email";
$stm = $con->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$rol = $pers->rol;
$voornaam = $pers->voornaam;
$achternaam = $pers->achternaam;
$_SESSION["voornaam"] = $voornaam;
$_SESSION["achternaam"] = $achternaam;
$_SESSION["rol"] = $rol;
if($_SESSION["rol"] == 'Admin') {
header("location:index.php");
} else
if($_SESSION["rol"] == 'Gebruiker') {
header("location:../index.php");
} else {
header("location:login.php");
}
}
}
else
{
$message = '<label>Wrong input</label>';
}
}
}
【问题讨论】:
-
可能
$result为假或不包含任何行? -
它包含行
-
为什么不尝试在进入循环之前将 $result 的值打印到日志或控制台。与您期望它包含的值相比,它包含的值有问题。
-
你试过打印$count吗
-
出现这种情况的原因可能是您的查询无法返回结果。尝试 print_r $result 里面的内容,你会看到。顺便说一句,使用准备好的语句不需要 htmlspecialchars 或其他清理。删除它,看看结果是否改变
标签: php html sql session foreach