Select only 1 record with the same category and Hidden in the other

Asked

Viewed 440 times

1

I have to list some Humbs of the same category only I want to appear 1 for the user and others stay as Hidden in the code. I’m seeing with GROUP BY categoria only if I do it and give while() it lists only one per category and the others that would have to stay as Hidden do 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++;
}
?>
  • I don’t understand the problem, you can post part of the code?

  • @Papacharlie I have a field called "category" and in it has the category of record. I have for example 10 records all with the same category. I wanted to pick up and list on the screen 1 record and the other 9 list too, only that leave with the style="display:Hidden"

  • It excludes my previous answer because it was incomplete, I did not change it so that the comments were not meaningless... I posted a new answer based on what I understood of gave problem.

2 answers

1

The behavior of GROUP BY That’s right, join the same records and show only 1. You must use the ORDER BY to join the equals and show one after the other, at the end of while memorize 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'];
}

0

I ran tests with the example and it’s running as you explained.
I tried to comment on 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 the grouping

• category['A'] 10 records
» 1st Visible and 9 Hidden

• category['A'] 15 records
» 1º 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
» 1º Visible and 4 Hidden(CAT-A) + 1 Visible and 10 Hidden(CAT-B)

Browser other questions tagged

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