為什麼我的登入表單無法連線到 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中文網其他相關文章!