How can the PHP code be optimized to retrieve and send data for the logged-in user more efficiently?

To optimize the PHP code for retrieving and sending data for the logged-in user more efficiently, you can utilize sessions to store user data after they log in. This way, you can avoid querying the database repeatedly for user information on each page load. By storing user data in sessions, you can access it quickly and efficiently whenever needed throughout the user's session.

<?php
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // Retrieve user data from session
    $user_id = $_SESSION['user_id'];
    
    // Use $user_id to fetch user data from database if needed
    // Send data to user or perform actions based on user data
} else {
    // Redirect user to login page if not logged in
    header("Location: login.php");
    exit();
}
?>