How can PHP sessions be utilized to display data specific to the currently logged-in user in a web application?

To display data specific to the currently logged-in user in a web application, you can utilize PHP sessions to store the user's unique identifier (such as their user ID) upon login. Then, retrieve this identifier from the session on each page load to fetch and display the user-specific data from the database.

// Start the session
session_start();

// Set the user ID in the session upon login
$_SESSION['user_id'] = $user_id;

// Retrieve the user ID from the session
$user_id = $_SESSION['user_id'];

// Fetch and display user-specific data using the user ID
$query = "SELECT * FROM users WHERE id = $user_id";
// Execute the query and display the data