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();
?>
Related Questions
- How can the order of execution of code be controlled when using eval() in PHP?
- What are some recommended best practices for handling and processing bbcode in PHP to prevent errors and ensure proper functionality?
- What are common pitfalls when querying a MySQL database using PHP, and how can they be avoided?