Filter first result

Asked

Viewed 96 times

2

Have some way to filter in php the first result of a query ?

Example:

$query = mysql_query("SELECT * FROM teste2 ORDER BY 'id' DESC") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {

if (RESULTADO == PRIMEIRO RESULTADO) {
echo "PRIMEIRO - $row[teste]";
}
else {
echo "NÃO É O PRIMEIRO - $row[teste]";
}

}

1 answer

5


Normal Path - Pure PHP:

There are several ways, here is a well didactic:

$query = mysql_query("SELECT * FROM teste2 ORDER BY id DESC")
   or die( mysql_error() );

// usei um contador para você poder testar outras linhas em vez da primeira, se quiser.

$contador = 1;
while ($row = mysql_fetch_array($query)) {
   if ( $contador == 1 ) {
      echo 'PRIMEIRO - '.$row['teste'];
   } else {
      echo 'NÃO É O PRIMEIRO - '.$row['teste'];
   }

   // Aqui, aumentamos o contador a cada linha.
   // Se preferir, tire a linha de baixo e ponha o ++ no $contador do if.
   $contador++ 
}

Note that the solution is entirely solved with PHP. Still with PHP, if it is only the first differentiated line, there is a much simpler alternative:

$query = mysql_query("SELECT * FROM teste2 ORDER BY id DESC")
   or die( mysql_error() );

if ( $row = mysql_fetch_array($query) ) {
   echo 'PRIMEIRO - '.$row['teste'];
}

while ( $row = mysql_fetch_array($query) ) {
   echo 'NÃO É O PRIMEIRO - '.$row['teste'];
}

In this way, the first line is solved in the if, and if there are more, the while shows the following.

I could have put the while within the if for it not to be used for nothing if the result came empty, but the gain would be virtually nil, and the immense readability loss.


Complicated path - counting lines with Mysql:

If you needed to know which line is on the Mysql side, you could complicate it this way:

mysql_query('SET @i = 0'); // inicializamos i
$query = mysql_query('SELECT (@i:=@i+1) AS linha, name FROM teste2 ORDER BY id DESC')
   or die( mysql_error() );

while ($row = mysql_fetch_array($query)) {
   if ( $row['linha'] == 1 ) {
      echo 'PRIMEIRO - '.$row['teste'];
   } else {
      echo 'NÃO É O PRIMEIRO - '.$row['teste'];
   }
}

I just showed this second way to say that it exists. Avoid it until you have a real need to count the server-side lines. The solutions with pure PHP are the right ones, if the real problem is simple as explained in the question.

Note that I have changed some things in your syntax, which have nothing to do with the main problem, but which would also hinder your result.

  • that’s what I wanted, it’s so simple just add a counting variable, lack of logic...!!!

Browser other questions tagged

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