How can session variables be correctly used in a MySQL query in PHP?

When using session variables in a MySQL query in PHP, it is important to properly sanitize the input to prevent SQL injection attacks. One way to do this is by using prepared statements with placeholders for the session variables in the query. This ensures that the values are properly escaped before being included in the query.

// Assuming session variables have been set earlier in the code
$userId = $_SESSION['user_id'];

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

// Prepare a SQL statement with a placeholder for the session variable
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");

// Bind the session variable to the placeholder in the query
$stmt->bind_param("i", $userId);

// Execute the query
$stmt->execute();

// Fetch the results
$result = $stmt->get_result();

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the statement and connection
$stmt->close();
$mysqli->close();