How can one efficiently store and retrieve user information from a MySQL database in PHP for authentication purposes?
To efficiently store and retrieve user information from a MySQL database in PHP for authentication purposes, you can use prepared statements to prevent SQL injection attacks and securely hash passwords before storing them. When retrieving user information for authentication, compare the hashed password from the database with the hashed password input by the user.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute SQL query to store user information
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $hashed_password);
$username = "user123";
$password = "password123";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt->execute();
// Prepare and execute SQL query to retrieve user information for authentication
$stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "user123";
$stmt->execute();
$stmt->bind_result($stored_password);
$stmt->fetch();
if (password_verify($password, $stored_password)) {
echo "Authentication successful";
} else {
echo "Authentication failed";
}
// Close connection
$stmt->close();
$conn->close();