Should user IDs be stored in sessions for better data retrieval in PHP applications?

Storing user IDs in sessions can be a good practice for better data retrieval in PHP applications. By storing the user ID in a session variable, you can easily access it throughout the user's session without the need to repeatedly query a database for the ID. This can improve performance and simplify your code.

// Start the session
session_start();

// Set the user ID in a session variable
$_SESSION['user_id'] = $user_id;

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