How to group results from a query?

Asked

Viewed 37 times

1

I have the following consultation with the name of the recipe and the ingredients:

$query = ("
SELECT r.receita, i.ingrediente
FROM ptp_receitas r, ptp_receitas_ingredientes ri, ptp_ingredientes i
WHERE r.id = ri.idreceita
AND ri.idingrediente = i.id
AND r.id = ".$rid);
$db -> setQuery($query);
$results = $db -> loadObjectList();
foreach($results as $row){
    echo '<h1>'.$row->receita.'</h1>';
    echo '<h2>Lista de Ingredientes:</h2>';
    echo $row->ingrediente;

}

The problem is that this way it repeats the name of the recipe in all lines of the ingredient, for example:

Receita de Arroz
arroz
Receita de Arroz
sal

I wanted you to come:

Receita de arroz
arroz
sal

1 answer

3


Make the following logic with an auxiliary variable that will solve your problem:

$query = ("
SELECT r.receita, i.ingrediente
FROM ptp_receitas r, ptp_receitas_ingredientes ri, ptp_ingredientes i
WHERE r.id = ri.idreceita
AND ri.idingrediente = i.id
AND r.id = ".$rid);
$db -> setQuery($query);
$results = $db -> loadObjectList();

$count = 0;
foreach($results as $row){
    if($count != $row->idreceita){
        echo '<h1>'.$row->receita.'</h1>';
        echo '<h2>Lista de Ingredientes:</h2>';
        $count=$row->idreceita;
    }
    echo $row->ingrediente;

}

That way, it will print <h1> Nome da Receita</h1> and the line of <h2> only 1x per recipe.

  • Perfect, I just changed the idreceita by id and put the r.id in SELECT. Thanks!!!

  • All right! I’m glad it worked out ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.