PHP注册表单异常:除密码外其余数据均可存入MySQL数据库
Hey there, let's break down why your password isn't making it into the database—there's a tiny but critical mistake in your code, plus a few other things to check:
1. 最关键的拼写错误(直接导致问题)
Look at this line in your signup.inc.php:
$hashedPwd = password_hash($pwd, PASSWORD_DEFALUT);
You misspelled the PHP constant PASSWORD_DEFAULT—you wrote DEFALUT instead of DEFAULT (missing the U at the end).
Since PHP doesn't recognize the misspelled constant, it treats it as an unquoted string ("PASSWORD_DEFALUT"), which isn't a valid algorithm for password_hash(). This breaks the hashing process entirely, so nothing gets stored in the user_pwd field.
2. 数据库字段验证
Make sure your users table's user_pwd column is set up correctly:
- Use
VARCHAR(255)as the field type (the default bcrypt hash fromPASSWORD_DEFAULTis 60 characters long, so 255 gives you plenty of room for future algorithm changes) - Avoid using shorter lengths or
TEXT(thoughTEXTworks,VARCHARis more appropriate here)
3. 添加错误调试(帮你快速排查未来问题)
Right now, your code doesn't check if the database insert actually succeeds. Add this after mysqli_query to see any database errors:
$sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');"; $result = mysqli_query($conn, $sql); if (!$result) { die("Insert failed: " . mysqli_error($conn)); }
This would have immediately shown you an error related to the invalid hash algorithm, making the problem easier to spot.
修正后的代码片段
Here's the fixed version of the hashing and insert section:
else{ // 修正常量拼写 $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT); $sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');"; $result = mysqli_query($conn, $sql); // 添加错误检查 if (!$result) { die("数据库插入失败: " . mysqli_error($conn)); } header("Location: ../signup.php?signup=success"); exit(); }
额外建议:避免SQL注入
While you're using mysqli_real_escape_string, a safer approach is to use prepared statements instead. This eliminates the risk of SQL injection entirely, which is a critical security best practice for user input. Here's a quick example:
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT); $sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES (?, ?, ?, ?, ?);"; $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, "sssss", $first, $last, $email, $uid, $hashedPwd); mysqli_stmt_execute($stmt);
内容的提问来源于stack exchange,提问作者Piotr

