How can the PHP code be optimized to handle login authentication with two different tables more efficiently?

To optimize the PHP code for handling login authentication with two different tables more efficiently, you can use a single query to check both tables for the user credentials. This can be achieved by using UNION in the SQL query to combine the results from both tables.

// Assuming $username and $password are the user input values

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

// Prepare the SQL query to check both tables for user credentials
$query = "SELECT * FROM table1 WHERE username = '$username' AND password = '$password' 
          UNION 
          SELECT * FROM table2 WHERE username = '$username' AND password = '$password'";

// Execute the query
$result = $mysqli->query($query);

// Check if a row was returned
if ($result->num_rows > 0) {
    // Authentication successful
    echo "Login successful!";
} else {
    // Authentication failed
    echo "Invalid username or password";
}

// Close the database connection
$mysqli->close();