我正在嘗試使用 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'); }}
1 回答

達令說
TA貢獻1821條經驗 獲得超6個贊
header('Location: ...');就像一個終結者:它將瀏覽器重定向到另一個頁面。在您的循環的第一次運行中,您以兩種可能的方式之一使用它。你想要的是:
foreach ($result as $r) {
if ($username == $r['username'] && $password == $r['password']) {
header('Location: mainPage.php');
die();
}
}
header('Location: login.php');
順便說一句,如果僅獲取用戶的用戶記錄并檢查 0 或 1 個結果,則可以對此進行優化。
很重要
您將明文密碼存儲在數據庫中。不要這樣做。在某些州,這是法律禁止的!
- 1 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消