为什么我的登录表单无法连接到 MySQL 数据库?
您的登录表单无法连接到 MySQL 数据库,因为有几个原因。以下响应提供了解决潜在问题的全面解决方案:
安全密码处理:
通过使用密码哈希来保护用户密码至关重要以明文形式存储它们。利用password_hash()等函数对密码进行单向加密,确保其安全性。
SQL注入预防:
避免使用user-直接在 SQL 查询中提供数据。使用准备好的语句并绑定参数来防止恶意 SQL 注入攻击,这可能会损害您的数据库。
mysqli 功能与代码示例:
register.php
// DB Credentials $servername = "localhost"; $username = "root"; $password = ""; $dbname = "user_accounts2"; // Secure Connection mysqli_report(MYSQLI_REPORT_ALL); error_reporting(E_ALL); ini_set("display_errors", 1); // Database Connection $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // User Registration if (isset($_POST['register'])) { $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); // Password Hashing $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Prepared Statement and Parameter Binding $stmt = $conn->prepare("INSERT INTO user_accounts2 (email, password) VALUES (?, ?)"); $stmt->bind_param("ss", $email, $hashed_password); // Query Execution $stmt->execute(); } // Close Connection $stmt->close(); $conn->close();
login.php
// DB Credentials and Secure Connection Same as register.php // User Login if (isset($_POST['login'])) { $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); // Prepared Statement and Parameter Binding $stmt = $conn->prepare("SELECT * FROM user_accounts2 WHERE email = ?"); $stmt->bind_param("s", $email); // Query Execution $stmt->execute(); $result = $stmt->get_result(); if ($row = $result->fetch_assoc()) { // Password Verification if (password_verify($password, $row['password'])) { echo "Logged in successfully!"; } else { echo "Invalid credentials"; } } else { echo "User not found"; } // Close Statement and Connection $stmt->close(); $conn->close(); }
pdo 功能与代码示例:
有关使用 PDO 进行用户身份验证的详细示例,请参阅此资源:[答案:PDO 用户身份验证](https://stackoverflow.com/questions/5926241/php-pdo-user -身份验证/5927236#5927236)
以上是为什么我的 PHP 登录表单无法连接到 MySQL?的详细内容。更多信息请关注PHP中文网其他相关文章!