Query-Based Approach:
To efficiently retrieve the sum of a column, leverage SQL's built-in aggregation function:
SELECT SUM(column_name) FROM table_name;
PDO Implementation:
// Prepare the query $stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes'); // Execute the query $stmt->execute(); // Fetch the results $row = $stmt->fetch(PDO::FETCH_ASSOC); // Retrieve the sum $sum = $row['value_sum'];
mysqli Implementation:
// Execute the query $result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes'); // Fetch the results $row = mysqli_fetch_assoc($result); // Retrieve the sum $sum = $row['value_sum'];
Note:
The above is the detailed content of How to Calculate Column Sums in MySQL using PHP?. For more information, please follow other related articles on the PHP Chinese website!