What are the best practices for handling and displaying data fetched from MySQL in PHP, especially when dealing with multiple types of data?

When handling and displaying data fetched from MySQL in PHP, especially when dealing with multiple types of data, it is important to properly sanitize and format the data before outputting it to the user. This includes using functions like htmlspecialchars() to prevent XSS attacks and ensuring that data types are correctly handled to avoid errors or unexpected behavior.

// Fetch data from MySQL
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Loop through the results and display the data
while ($row = mysqli_fetch_assoc($result)) {
    $id = htmlspecialchars($row['id']);
    $name = htmlspecialchars($row['name']);
    $age = (int) $row['age'];

    echo "ID: $id, Name: $name, Age: $age <br>";
}