What are the advantages of using MySQL in conjunction with PHP for user authentication compared to a standalone PHP script?
When using MySQL in conjunction with PHP for user authentication, you can securely store user credentials in a database, allowing for easier management and scalability. Additionally, MySQL provides built-in encryption functions for password hashing, adding an extra layer of security to user data. By separating authentication logic from the application code, you can easily update and maintain the authentication process without affecting the rest of the application.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve user credentials from database
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
echo "Login successful!";
} else {
echo "Invalid username or password";
}
} else {
echo "Invalid username or password";
}
$conn->close();