简体   繁体   中英

Identifying the 3rd row in a MySQL while loop

What I'm doing is for every 3rd outputted MySQL database row, I'll run a custom function that outputs differently. How would I identify every 3rd row?

Very simple. You can do something like this:

$i = 1;
while ( $array = mysql_fetch_assoc($result) )
{
   if ($i % 3 == 0)
   {
      // call other function
   }
   $i++;
}

Please, note the use of the modulus operator .

This will call the specific function every 3rd row

$cpt = 1;
while ($row = mysql_fetch_assoc($result)) {
 if($cpt % 3 == 0){
  do_something_custom();
 }
 $cpt++;
}

I guess this will be kinda repeating the others , but :

$i = 1;
while ( $data = $pdo_statement->fetch( PDO::FETCH_ASSOC ) )
{
    if ( $i++ % 3 === 0 )
    {
        // do stuff
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM