What is the best practice for querying and summing data from a database in PHP?
When querying and summing data from a database in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. This involves using placeholders in the SQL query and binding parameters to those placeholders. Once the data is fetched from the database, you can then sum up the values as needed using PHP code.
<?php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL query with a placeholder for the sum
$stmt = $pdo->prepare("SELECT SUM(column_name) AS total_sum FROM my_table WHERE condition = :condition");
// Bind the parameter to the placeholder
$stmt->bindParam(':condition', $condition_value);
// Execute the query
$stmt->execute();
// Fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Get the sum value
$total_sum = $result['total_sum'];
// Output the total sum
echo "Total sum: " . $total_sum;
?>