Help - Search - Members - Calendar
Full Version: Alternating row colours
Pixel2Life Forum > Member Tutorials and Requests > Forum Tutorial Archives > PHP Tutorials
Matthew.
Another tutorial written by me a while back, enjoy victory.gif


In this tutorial i will be showing you how to achieve alternating row colours using PHP.
Something like this will be our outcome:



What we will use

In the tutorial i shall use these functions (linked for reference):

Comparason operators

While() (loops)

define()

And of course of the standard mysql functions for example's sake.


Standard code:

This code is not part of the tutorial, but merely for connecting to the database, Jst copy it if you wish.

CODE
<?php
$config = array(
             'user' => 'username',
             'pass' => 'password',
             'DB' => 'database_name',
             'host' => 'localhost'
            );
    @mysql_connect($config['host'], $config['user'], $config['pass']) or die(mysql_error());
    @mysql_select_db($config['DB']) or die(mysql_error());




The learning bit....

Yup,time to learn (awwww!)

First off im going to use define(); to set the 2 BG colours we want. These are the colours that will alternate.

define is very simple:

define( mixed value, case sensitive value )

Note that since were using HEX we dont need to worry about case's, btu normall you should take note of it.

OK.

CODE
define("Bg1", "#FFF");
define("Bg2", "#EEE");


So we set one variable "Bg1" and one "Bg2" kinda self explanatory huh? The first is #FFF (white) and the 2nd #EEE (grey---ish).


The next 2 lines are again, basic stuff.

CODE
    $i = 0;
    $Query = @mysql_query("SELECT title FROM `example` ORDER BY id DESC") or die('Error: '.mysql_error());


We are setting $i as 0 as we are going to sue it in a loop to alternate the colour values, the 2nd line in the mysql query that you change to suit your needs.

(notice that we are supressing error's using @ and creating our own at the end.)



Now for the real code, This part changes the colours are echo's out the data.

CODE
while( $row = mysql_fetch_array($Query) )
{                 
        $i = ($i > 1 ? '0' : $i );
        $loopedBG = ($i > 0 ? Bg1 : Bg2 );                         
        echo "<div style='background-color: $loopedBG;'>{$row['title']}</div>";
        
                $i++;                
}



First we begin a while() loop, this takes all the data from the query and displays it.

CODE
$i = ($i > 1 ? '0' : $i );


This is a ternary operator, as explan in 2 past tutorials, basically,it works like this:

string name = (condition ? value if true: value if false);

So this one, it checking if $i is greater than 1, if it is, reset i to 0, if not carry on with its current value tongue.gif

CODE
$loopedBG = ($i > 0 ? Bg1 : Bg2 );


This line is what changes the colour, is laymens terns its:

IF $i is greater than Zero, value is Bg1 if not value if Bg2

And remember we set Bg1 and Bg2 earlier.

CODE
echo "<div style='background-color: $loopedBG;'>{$row['title']}</div>";


This is again, self explanatory, we are simply echo'ing the data within a DIV. The DIV has a srtyle property and notice that the colour is not set by you, but by the varable $loopedBG


Notice there are curly braces around $row['title'], this is because we are access'ing an array within double quotes and is standard practice.

Now,

I know what your thinking, "We did all this checking if $i has changed, but it doesnt, because we havent done anything to change it....?".

Well, you'd be correct, we havent, but now we have!....

CODE
$i++;


This ADDS 1 to the current value of $i every time the loop goes round.

Its the same as using

CODE
$i = $i +1;
or
$i = $i++;


But the above would be pointless tongue.gif


Now we simply close the loop and end the script!!

Done!!

Heres the complete code:

CODE
<?php
$config = array(
             'user' => 'username',
             'pass' => 'password',
             'DB' => 'database_name',
             'host' => 'localhost'
            );
    @mysql_connect($config['host'], $config['user'], $config['pass']) or die(mysql_error());
    @mysql_select_db($config['DB']) or die(mysql_error());
        
    define("Bg1", "#FFF");
    define("Bg2", "#EEE");

    $i = 0;
    $Query = @mysql_query("SELECT title FROM `example` ORDER BY id DESC") or die('Error: '.mysql_error());            
        while( $row = mysql_fetch_array($Query) )
        {
                     
                 $i = ($i > 1 ? '0' : $i );
                $loopedBG = ($i > 0 ? Bg1 : Bg2 );        
                     
                 echo "<div style='background-color: $loopedBG;'>{$row['title']}</div>";
                 $i++;            
        }
?>



Enjoy bigwink.gif bigwink.gif
Indigo
Thanks a lot for sharing:)
You could probably just use $i = 1; too.

Can you please explain why you´re using define instead of just $bg1 = #fff; and then use ($i > 0 ? $bg1 : $bg2 ); ?
Matthew.
Its just my way, define is usually not used this way i will admit, its more suited to database connections details and similar where you dont wish the vriable to be changed by someone who's just read a nice little tutorial on script owning. bigwink.gif

Its a habit lol. It really doesnt matter though tongue.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.