How can one ensure that the login functionality using MySQLi and Prepared Statements in PHP is secure and protected against SQL injection attacks?

To ensure that the login functionality using MySQLi and Prepared Statements in PHP is secure and protected against SQL injection attacks, one should always use prepared statements with bound parameters to prevent malicious SQL injection attempts. This involves properly sanitizing and validating user input before executing any SQL queries in order to prevent attackers from manipulating the query.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check if the connection was successful
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare a SQL statement with placeholders for username and password
$stmt = $mysqli->prepare("SELECT id FROM users WHERE username = ? AND password = ?");

// Bind the parameters to the placeholders
$stmt->bind_param("ss", $username, $password);

// Set the username and password variables
$username = $_POST['username'];
$password = $_POST['password'];

// Execute the prepared statement
$stmt->execute();

// Bind the result to a variable
$stmt->bind_result($user_id);

// Fetch the result
$stmt->fetch();

// Check if a user was found
if ($user_id) {
    echo "Login successful!";
} else {
    echo "Invalid username or password.";
}

// Close the statement and the connection
$stmt->close();
$mysqli->close();