If you want every rate
to come on a separate line, this is enough:
SELECT rate, COUNT(*) AS row_count
FROM tb_comment
WHERE id_mark=:post_id
GROUP BY rate
Note that I changed the AS rate
to AS rate_sum
, and added the rate
original in SELECT
. Avoid using AS
with names that already exist in the table, not to be confused. If you need to, I put the example of COUNT()
as well.
If you prefer, you can add a ORDER BY rate
, or ORDER BY rate DESC
to determine the order from the smallest to the largest, or the inverse.
Remember to swap loop to get all the lines.
if($count > 0){
$loop = $resultone->fetchAll();
foreach ($loop as $show) {
echo $show['rate'] . ' - ' . $show['row_count'];
}
}
You can simplify too:
while ( $show = $resultone->fetch( PDO::FETCH_ASSOC ) ) {;
echo $show['rate'] . ' - ' . $show['row_count'];
}
Mounting the code:
$query =
'SELECT rate, COUNT(*) AS row_count FROM tb_comment WHERE id_mark=:post_id GROUP BY rate';
$resultone = $conexao->prepare($query);
$resultone->bindParam(':post_id', $post_id, PDO::PARAM_STR);
$resultone->execute();
while ( $show = $resultone->fetch( PDO::FETCH_ASSOC ) ) {
echo $show['rate'] . ' - ' . $show['row_count'] . "<br>\n";
}
And, if you want to use the results separately:
$query =
'SELECT rate, COUNT(*) AS row_count FROM tb_comment WHERE id_mark=:post_id GROUP BY rate';
$resultone = $conexao->prepare($query);
$resultone->bindParam(':post_id', $post_id, PDO::PARAM_STR);
$resultone->execute();
$ratings = array( 0, 0, 0, 0, 0 );
while ( $show = $resultone->fetch( PDO::FETCH_ASSOC ) ) {
$ratings[ (int) $show['rate'] ] = $show['row_count'];
}
for ( $i = 1; $i <= 5; $i++ ) {
echo $i . ' - ' . $ratings[$i] . "<br>\n";
}