Select count and sum rows in MySQLi database using prepared statements and PHP

January 24, 2024


$color = 'Red';

$query = "SELECT 
COUNT(id) AS total_items, 
SUM(price) AS total_price, 
FROM items
WHERE deleted != 'y'
AND color = ?
";

$stmt = $mysqli -> prepare($query);
$stmt -> bind_param("s", $color);
$stmt -> execute();
$result = $stmt -> get_result();

$num_rows = $result -> num_rows;

if($num_rows > 0){

$row = $result -> fetch_assoc();

echo $row['total_items'] . '< br >';
echo $row['total_price'] . '< br >';

} else {

echo 'No results were found';

}


Comments

There are no comments.


Comment on this Article

Your email address will never be published. Comments are usually approved within an hour or two. (to prevent spam)