How can the use of MySQL queries in PHP help improve the accuracy and efficiency of online/offline status checks?

When checking online/offline status of users in a web application, using MySQL queries in PHP can help improve accuracy and efficiency by directly querying the database to retrieve real-time status information. This eliminates the need for potentially outdated or cached data, ensuring that the status check is always up-to-date. Additionally, by leveraging the power of SQL queries, complex status checks can be easily implemented and executed efficiently.

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check if user with ID 1 is online
$user_id = 1;
$sql = "SELECT online_status FROM users WHERE id = $user_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if ($row["online_status"] == 1) {
        echo "User with ID $user_id is online.";
    } else {
        echo "User with ID $user_id is offline.";
    }
} else {
    echo "User with ID $user_id not found.";
}

$conn->close();