How can the use of JOIN in SQL queries improve the efficiency and readability of PHP scripts, particularly when checking for user credentials?

Using JOIN in SQL queries can improve the efficiency and readability of PHP scripts by allowing us to fetch related data from multiple tables in a single query. This eliminates the need for multiple queries and reduces the amount of data processing required in the PHP script. When checking for user credentials, JOIN can help retrieve user information and credentials from different tables in a database, making the authentication process more streamlined and efficient.

<?php
// Establish a database connection
$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);
}

// SQL query using JOIN to fetch user credentials
$sql = "SELECT users.username, credentials.password
        FROM users
        JOIN credentials ON users.user_id = credentials.user_id
        WHERE users.username = 'john_doe'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // User credentials found
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"]. " - Password: " . $row["password"]. "<br>";
    }
} else {
    // User credentials not found
    echo "User not found or invalid credentials.";
}

$conn->close();
?>