I have an error in wanting to add an error message when there are no votes for a product.
When there are no votes in any product, all the variables of the query return the value in print, 0
apparently it is taking the value 0
as valid data as if it were a value vote0
How can I create a condition to the variables or to while ($stmt->fetch())
which if all the values of the query return the value 0
it shows the error message?
Note: That the condition or parameter is only executed if the entire query of its variables returns a value
0
if there is a numerical value of0.5
not executed.
$id_product = 1;
$stmt = $con->prepare("SELECT SUM(rating IN (4.5, 5))/COUNT(*)*100 AS pct_5_star,
SUM(rating IN (3.5, 4))/COUNT(*)*100 AS pct_4_star,
SUM(rating IN (2.5, 3))/COUNT(*)*100 AS pct_3_star,
SUM(rating IN (1.5, 2))/COUNT(*)*100 AS pct_2_star,
SUM(rating IN (0.5, 1))/COUNT(*)*100 AS pct_1_star,
SUM(CASE WHEN rating IN (4.5, 5) THEN rating ELSE 0 END) AS in_5_star,
AVG(rating) AS avg_rating
FROM ratings
WHERE id_product=?");
$stmt->bind_param("i",$id_product);
$stmt->execute();
$stmt->bind_result($pct_5_star, $pct_4_star, $pct_3_star, $pct_2_star, $pct_1_star, $in_5_star, $avg_rating);
while ($stmt->fetch()) {
echo "5 estrellas " . number_format($pct_5_star). "% <br />";
echo "4 estrellas " . number_format($pct_4_star). "% <br />";
echo "3 estrellas " . number_format($pct_3_star). "% <br />";
echo "2 estrellas " . number_format($pct_2_star). "% <br />";
echo "1 estrellas " . number_format($pct_1_star). "% <br /><br />";
echo "<b>Promedio:</b> " . number_format($avg_rating,1). "% <br />";
} else {
echo "No existe votos de este producto";
}
I hope I understand the question well.
Adds all the variables and if the sum is zero sends the error.
However if from the query you do not want those results use
HAVING
So:
You could use the calculation
AVG
that you are already using to obtain the average of the total result, in case no results were found, the variable$avg_rating
will0
also be, for this you create a check if said variable is greater than0
to show your results, otherwise you launch a message mistake.Example:
Now you could also calculate the votes cast, that is, if there is a vote, you show the statistics, and if there are no votes, you throw the error message.
This way you also get the total votes cast for your stats, I just added one more calculation to your statement,
COUNT(*) votos
.Alternative example: