Unable to Connect Login Form to MySQL Database
This inquiry pertains to implementing user login functionality that verifies against a MySQL database. The user expects to enter a username and password, which should be validated against the stored credentials in the database. Unfortunately, while the form submits without errors, the desired functionality is not achieved.
The root cause of this issue lies in the lack of protection against SQL injection attacks and the insecure storage of passwords in plain text in the database. To address these concerns, it is recommended to:
Register.php:
<code class="php">// Replace previous code with the following: session_start(); if (isset($_SESSION['userid'])) { // Redirect to safe page } if (isset($_POST['register'])) { $email = $_POST['email']; $password = $_POST['password']; // Cleartext password from user // New code for password hashing $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Database connection and query $host = "localhost"; $dbname = "database_name"; $user = "username"; $pass = "password"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("INSERT INTO user_accounts (email, password) VALUES (?, ?)"); $stmt->execute([$email, $hashed_password]); // Redirect to login page $conn = null; } catch (PDOException $e) { throw $e; } }</code>
Login.php:
<code class="php">// Replace previous code with the following: session_start(); if (isset($_SESSION['userid'])) { // Redirect to safe page } if (isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['password']; // Cleartext password from user // Database connection and query $host = "localhost"; $dbname = "database_name"; $user = "username"; $pass = "password"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Get hashed password from database $stmt = $conn->prepare("SELECT password FROM user_accounts WHERE email = ?"); $stmt->execute([$email]); $hashed_db_password = $stmt->fetchColumn(); if (password_verify($password, $hashed_db_password)) { // User authenticated successfully $_SESSION['userid'] = true; // Redirect to safe page } else { // Authentication failed } $conn = null; } catch (PDOException $e) { throw $e; } }</code>
With these code modifications, user login should now function properly by securely interacting with the MySQL database, preventing both SQL injection attacks and the compromise of user passwords.
The above is the detailed content of Why is My Login Form Not Connecting to My MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!