In what ways can the described login script be optimized for scalability and reusability in PHP projects?

To optimize the described login script for scalability and reusability in PHP projects, we can refactor the code to separate concerns by using functions for repetitive tasks, implementing error handling, and utilizing prepared statements to prevent SQL injection attacks.

<?php
function login($username, $password) {
    // Connect to the database
    $conn = new mysqli("localhost", "username", "password", "database");

    // Check for connection errors
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Prepare the SQL statement
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();

    // Check if the user exists
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        // User authenticated
        return true;
    } else {
        // User not found or password incorrect
        return false;
    }

    // Close the connection
    $stmt->close();
    $conn->close();
}

// Usage
$username = "john_doe";
$password = "password123";
if (login($username, $password)) {
    echo "Login successful";
} else {
    echo "Login failed";
}
?>