What are the best practices for structuring PHP code that involves querying multiple tables for user authentication?

When structuring PHP code for user authentication that involves querying multiple tables, it is best practice to create a separate function for each table to keep the code organized and maintainable. This allows for easier debugging and future updates. Additionally, using prepared statements with parameterized queries can help prevent SQL injection attacks.

// Function to query the users table for authentication
function authenticateUser($username, $password) {
    // Perform query to check if user exists in users table
    // Return true if authentication successful, false otherwise
}

// Function to query the roles table to get user roles
function getUserRoles($username) {
    // Perform query to fetch roles for the user from roles table
    // Return an array of roles associated with the user
}

// Function to check if user has specific role
function hasRole($username, $role) {
    $roles = getUserRoles($username);
    return in_array($role, $roles);
}

// Example usage
if (authenticateUser($username, $password)) {
    if (hasRole($username, 'admin')) {
        // User is an admin
    } else {
        // User is not an admin
    }
} else {
    // Authentication failed
}