Select only 1 record with equal category and hidden in others

1

I have to list a few thumbs of the same category, but I want it to appear 1 for the user and the others to be hidden in the code. I'm seeing with GROUP BY category only if I do this and I give while() it lists only one per category and the others that would have to stay as hidden will not stay.

<?php

$SQL = mysql_query("SELECT * FROM projetos");

$i = 0;

while($e = mysql_fetch_array($SQL)){

echo $e["categoria"];

if($i > 0){

echo "<div style='display:none;'>".$e["categoria"]."</div>";
$i = 0;
}

$i++;
}
?>
    
asked by anonymous 19.08.2014 / 07:59

2 answers

1

The behavior of GROUP BY is the same, join the same records and show only 1. You should use ORDER BY to join the equals and show one after the other, at the end of while memorizing the category to compare in the next record, as in the example below:

$categoria_anterior = NULL;

$SQL = mysql_query("SELECT * FROM projetos ORDER BY categoria, id");

while($e = mysql_fetch_array($SQL)){
    echo '<div' . ($e['categoria'] == $categoria_anterior ? ' style="display:none;"':'') . '>' .
        $e['categoria'] .
    '</div>';
    $categoria_anterior = $e['categoria'];
}
    
19.08.2014 / 13:09
0

I ran tests with the example and it is running as you explained. I tried to comment the code as much as possible in a simple way.

$limit = 10;
$counter = 1;
$categoria = null;

while( ... )
{
    // verifica se mudou a categoria, e inicia o contador se for maior que 1
    if( $categoria !== $row['categoria'] and $counter > 1 )
    $counter = 1;

    if( $counter === 1 )
    {
        echo $e['categoria'];
    }
    else
    {
        echo '<div style="display:none;">' . $e['categoria'] . '</div>';

        // reinicia o contador se for maior que o decimo item
        if( $counter === $limit ) $counter = 0;
    }

    // incrementa o contador e grava a categoria atual
    $counter++;
    $categoria = $e['categoria'];
}


  

Some situations to illustrate grouping

• Category ['A'] 10 records »1st visible and 9 hidden

• Category ['A'] 15 records
»1st visible and 9 hidden + 1 visible and 4 hidden

• category ['A'] 10 records | category ['B'] 5 records
»1 visible and 9 hidden (CAT-A) + 1 visible and 4 hidden (CAT-B)

• category ['A'] 5 records | category ['B'] 10 records
»1st visible and 4 hidden (CAT-A) + 1 visible and 10 hidden (CAT-B)

    
19.08.2014 / 10:22