What is the difference between using COUNT and SUM in a SQL query to aggregate data in PHP?
When using COUNT in a SQL query, it will return the number of rows that meet the specified criteria, while SUM will return the total sum of a specific column's values. So, if you want to count the number of rows in a table, use COUNT. If you want to calculate the total sum of a specific column, use SUM.
// Using COUNT to count the number of rows in a table
$query = "SELECT COUNT(*) FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$count = $row[0];
// Using SUM to calculate the total sum of a specific column
$query = "SELECT SUM(column_name) FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$sum = $row[0];
Related questions
-
subdomains PHP files organization
-
cron jobs automated email generation PHP
-
output buffering headers ob_start