What are some best practices for calculating and displaying total prices from a MySQL database using PHP?

When calculating and displaying total prices from a MySQL database using PHP, it is important to properly sanitize user input to prevent SQL injection attacks. Additionally, ensure that your query retrieves the necessary data for calculation and use PHP functions to perform the calculations accurately. Finally, format the total price appropriately before displaying it to the user.

<?php

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from database
$sql = "SELECT price FROM products";
$result = $conn->query($sql);

// Calculate total price
$totalPrice = 0;
while($row = $result->fetch_assoc()) {
    $totalPrice += $row['price'];
}

// Format total price
$totalPriceFormatted = number_format($totalPrice, 2);

// Display total price
echo "Total Price: $" . $totalPriceFormatted;

// Close database connection
$conn->close();

?>