Proffesor
Proffesor

Reputation: 2619

Insert line break after every two rows of database

I have a little script that prints a certain amount of rows in a mysql database.

Is there any way to make it so that after every second row it prints, there is a line break inserted?

Adding a line break after every row is simple, but I don't know how to add one after every other row. Is that possible?

Upvotes: 1

Views: 7346

Answers (6)

Deept Raghav
Deept Raghav

Reputation: 1460

$i=1;
while ($row = mysql_fetch_array($query))
{
    //your code
    if ($i % 2 == 0)
        echo '<br>';
    $i++;
}

Upvotes: 4

Eugen Rieck
Eugen Rieck

Reputation: 65304

If you need to do this inside the query for some reason, you could use something like

SELECT
  <your fields>,
  IF (((@rn:=@rn+1) % 3)=0,'<br>','') as brornot
FROM
  <your tables and joins>,
  (@rn:=0)

Upvotes: 0

Wes Crow
Wes Crow

Reputation: 2967

Depending on the language, something like this should do it: (in php) (where $arr is an array of results)

$str = '';
$i = 0;

for ($i=0; $i<count( $arr ); $i++)
{
   if ( ( $i + 1 ) % 2 === 0 )
   {
      $str .= $arr[$i] . '<br />';
   }
   else
   {
      $str .= $arr[$i];
   }
}

echo $str;

Upvotes: 1

Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Use php and modulo.

such as

if($i % 3)
  {
    echo '<br />'..

Upvotes: 0

Darvex
Darvex

Reputation: 3644

add new variable before the loop

$i = 0;

then in your loop add

if ($i != 0 && $i%2 == 0)
   echo '<br/>';

Upvotes: 3

Tomas
Tomas

Reputation: 59525

You write "script" but in tags you have PHP, so I suppose you need PHP code:

foreach ($rows as $row) {
    if ($i++ % 2) { 
         // this code will only run for every even row
    }
    ...
}

Upvotes: 4

Related Questions