What are the potential security risks of using user IDs stored in sessions for MySQLi queries in PHP?

Storing user IDs in sessions for MySQLi queries can lead to security risks such as session hijacking or session fixation attacks. To mitigate these risks, it is recommended to avoid directly using user IDs from sessions in SQL queries. Instead, you should validate and sanitize the input data before using it in your queries to prevent SQL injection attacks.

// Validate and sanitize the user ID from the session before using it in a MySQLi query
$user_id = filter_var($_SESSION['user_id'], FILTER_VALIDATE_INT);

// Prepare a SQL statement with a placeholder for the user ID
$stmt = $mysqli->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

// Fetch the data from the query result
while ($row = $result->fetch_assoc()) {
    // Process the data as needed
}