Question

I want to create a site, which displays a lot of records from a database. To make it more reader-friendly, I want to use a styling. One record is white background, the next blue, the next hhite again.

So I tried this:

<?php while ($info = mysql_fetch_array($data)){
PRINT "<tr>";
PRINT "<td>"  .$info['articlenr']. "</td>";
PRINT "<td>"  .$info['stock']. "</td>";
PRINT "</tr>";
PRINT "<tr>";
PRINT "<td bgcolor=#0066FF>"  .$info['articlenr']. "</td>";
PRINT "<td bgcolor=#0066FF>"  .$info['stock']. "</td>";
PRINT "</tr>";
}
?>

This works for the view, but the problem is, the blue record is the same as the white, not the next one, it just doubles the record and make it another color.

How can I do this right?

Was it helpful?

Solution

Use :nth-of-type(even) to get even/odd combination of color's.

Here is a demo example:

html:

<table>
<tr><td>item1</td>
</tr>
<tr><td>item2</td>
</tr>
<tr><td>item3</td>
</tr>
<tr><td>item4</td>
</tr>
</table>

css:

tr:nth-of-type(even) { background-color: #0066FF; }

Demo

OTHER TIPS

If you want to do this in PHP, you could do it like this :

<?php 
$iter = 0;
$color1 = 'red'; //can se hex code too, like #0066FF;
$color2 = 'blue';

while ($info = mysql_fetch_array($data))
{
    echo '<tr style="background-color:'.( ($iter%2==0) ? $color1 : $color2).';">';
    // rest of the printing stuff
    $iter++;
}
?>

Statement

($iter%2==0) ? $color1 : $color2

does this : it asks the question whether iterator (or row number) is even. If yes, the it takes color1. If not (row is uneven) it takes the second color.

PHP Smarty is good for doing this kind of stuff (iterating over colors and styles), but it may be difficult for beginners.

Can I offer some advice on your code? Your approach mixes PHP and HTML in a way that makes it difficult for your development environment to parse your HTML, and you can achieve the same with less keystrokes! Consider this approach instead:

<?php while ($info = mysql_fetch_array($data)): ?>
    <tr>
        <td><?php echo $info['articlenr'] ?></td>
        <td><?php echo $info['stock'] ?></td>
    </tr>
<?php endwhile ?>

Changes I've made:

  • Removed the duplicate row
  • Rendered everything in HTML mode, and opened PHP tags just for PHP code
  • Switched the loop to the colon form, which is often thought to be clearer in templates. Do carry on using the brace approach, however, in large chunks of code (e.g. classes)
  • Written PHP keywords in lower case
  • Used echo rather than print

Combine this with Joke_Sense10's answer for a full solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top