How can user-specific data be retrieved from a database during a session in PHP?

To retrieve user-specific data from a database during a session in PHP, you can store the user's unique identifier (such as their user ID) in a session variable when they log in. Then, use this identifier to query the database for the user's specific data during the session.

// Start the session
session_start();

// Assuming the user ID is stored in $_SESSION['user_id']
$user_id = $_SESSION['user_id'];

// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Query the database for user-specific data
$query = "SELECT * FROM users WHERE id = $user_id";
$result = $connection->query($query);

// Fetch the data
$user_data = $result->fetch_assoc();

// Use the user data as needed
echo "Welcome back, " . $user_data['username'] . "!";