MySQL Check if username and password matches in Database
To check if a given username and password match those stored in a MySQL database, you can use a SQL SELECT statement with a WHERE clause.
To check if a given username and password match those stored in a MySQL database, you can use a SQL SELECT statement with a WHERE clause to filter the results based on the provided username and password.
Here is an example of a secure PHP implementation using PDO and prepared statements:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'db_user', 'db_pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute([':username' => $username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
echo 'Login successful';
} else {
echo 'Invalid credentials';
}
?>In this example, :username is a named placeholder that prevents SQL injection. The query returns the user record, and password_verify() compares the provided password against the stored hash.
It is important to note that it is not a good practice to store passwords in plain text. You should hash passwords before storing them in the database (e.g., using password_hash()), and then verify the provided password against the stored hash using password_verify().
Also, it's recommended to use prepared statements instead of concatenating variables into the query to prevent SQL injection attacks.