我正在尝试使用php创建一个登录系统,该系统检查数据库中的用户名和密码。但是问题是,foreach中的if语句仅检查数据库中的最后一个值。为了使我的数据库中有5个具有用户名和密码的用户,我的foreach中的if语句仅检查我是否键入了最后一个用户的用户名和密码,但是如果我给它输入了用户名和密码,例如第二个用户,它将不会接受。
html代码:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Login</title>
</head>
<body>
<div class="top">
<div class="box">
<h2>Login</h2>
<form action="findAccount.php" method="post">
<div class="inputBox">
<input type="text" name="username">
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="password">
<label>Password</label>
</div>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
php代码:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=database_name', 'root', '');
$username = $_POST['username'];
$password = $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM tabel_name");
$sql->execute();
$result = $sql->fetchAll();
foreach ($result as $r) {
if ($username == $r['username'] && $password == $r['password']) {
header('Location: mainPage.php');
} else {
header('Location: login.php');
}
}
header('Location: ...');
就像终止符:它将浏览器重定向到另一个页面。在循环的第一轮中,您以2种可能的方式之一使用它。您想要的是:
foreach ($result as $r) {
if ($username == $r['username'] && $password == $r['password']) {
header('Location: mainPage.php');
die();
}
}
header('Location: login.php');
btw,如果仅获取用户的用户记录并检查0或1个结果,则可以优化此设置。
非常重要
您将清除密码存储在数据库中。不要这样在某些州,这是法律禁止的!