How do I select multiple values from the same table

1

How do I select values 1, 2, 3, 4, and 5 from the same table without doing that SELECT bundle?

<?php
$rateone    = 1;
$ratetwo    = 2;
$ratethree  = 3;
$ratefour   = 4;
$ratefive   = 5;

$query = "SELECT COUNT(rate) as rate FROM tb_comment WHERE id_mark=:post_id AND rate=:rateone";

    $resultone = $conexao->prepare($query);
    $resultone->bindParam(':post_id', $post_id, PDO::PARAM_STR);
    $resultone->bindParam(':rateone', $rateone, PDO::PARAM_INT);
    $resultone->execute();
    $count = $resultone->rowCount();

    if($count =1){
        $loop = $resultone->fetchAll();
        foreach ($loop as $show) {
            $Crateone = $show['rate'];
        }
    }

echo $Crateone;
?>
    
asked by anonymous 15.12.2015 / 04:59

1 answer

2

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"; 
}
    
15.12.2015 / 05:05