PHP登录功能异常:账号密码正确却提示无用户问题排查
Hey there, let's figure out why your login is failing even with correct credentials. After looking through your code, here are the key issues and fixes:
1. Critical Error: Missing Database Connection in mysqli_query
This is the most likely reason your login is failing. Your code calls:
$result=mysqli_query($sql);
But mysqli_query requires two parameters: first your database connection object (from connect.php, usually named $conn or $db), then the SQL query. Without the connection, the query never runs, $result becomes false, and mysqli_num_rows($result) returns 0—hence the "No User Found" message.
Fix it by adding your connection variable:
// Replace $conn with your actual connection variable from connect.php $result=mysqli_query($conn, $sql);
2. Password Handling Problems
You’re applying unnecessary transformations to the password and using insecure plain-text comparison:
stripcslashes(),htmlspecialchars(): If your database stores the original password (unmodified), these functions alter the input password, making it mismatch the stored value. Remove these from the password processing steps.- Plain-text password storage: This is a huge security risk. Always store hashed passwords. When registering users, use
password_hash($password, PASSWORD_DEFAULT)to hash the password before saving it to the database. Then, during login, verify withpassword_verify()instead of direct string comparison:// After fetching user info from DB if ($row == 1 && password_verify($password, $userinfo['password'])) { // Login success logic here }
3. Missing Session Initialization
You’re setting $_SESSION variables but never starting the session. Add session_start(); at the very top of your script (before any output, including the include statement):
session_start(); <?php include("connect.php"); // Rest of your code...
4. Add Error Debugging
To catch future issues, add error checking after your query to see if it’s failing:
$result = mysqli_query($conn, $sql); if (!$result) { die("Query failed: " . mysqli_error($conn)); }
This will print the exact MySQL error, which is invaluable for debugging.
Try these fixes one by one—starting with the missing database connection, since that’s the immediate showstopper.
内容的提问来源于stack exchange,提问作者natstv

