PHP
  Home arrow PHP arrow Alternating Row Colors With MySQL Results
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Alternating Row Colors With MySQL Results
By: Eric 'phpfreak' Rosebrock
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 12
    2003-04-01

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    You may wish to make you display stand out from the rest. A way of doing this, as Eric reports, is to use PHP to alternate the colors for every line of output.

    One of those popular ways to display your database queries is with alternating row colors inside of a table. Let's face it, if you are displaying any number of items inside your database, you should be using tables. This allows better formatting and better display of your results. If you would like to spice it up a little you can change the color of every other row inside your table and allow the results to be displayed in a manner which the user can read them easier. In this tutorial I will show you how.

    Let's start out with two basic colors for your row. I think I am going to use these colors because they fit the theme of our website. #CCFFCC for my odd number of rows and #BFD8BC for my even number of rows. Now that I have determined what colors I want my rows to be, I will move on.

    The first portion of any MySQL query inside PHP you should always put your table headers outside of your array, and then decide which of the table rows(<TR></TR>) and table data (<TD></TD>) you want to be inside the array for the results. Here's the code flow for this tutorial. I will break it down on the next page.

    // Begin your table outside of the array
    echo "<table width="100%" border="0" cellpadding="4" cellspacing="0">
        <tr>
            <td width="110"><b>Event Date</b></td>
            <td><b> Event Title</b></td>
        </tr>";
    // Define your colors for the alternating rows
    $color1 = "#CCFFCC"; 
    $color2 = "#BFD8BC"; 
    $row_count = 0;
    // Perform an statndard SQL query:
    $sql_events = mysql_query("SELECT date_format(event_date, '%M %d, %Y') as event_date,
    event_title FROM my_events ORDER BY event_date      ASC") or die (mysql_error());
    // We are going to use the "$row" method for this query. This is just my preference.
    while ($row = mysql_fetch_array($sql_events)) {
        $event_date = $row["event_date"];
        $event_title = $row["event_title"];
        /* Now we do this small line which is basically going to tell
        PHP to alternate the colors between the two colors we defined above. */
        $row_color = ($row_count % 2) ? $color1 : $color2;
        // Echo your table row and table data that you want to be looped over and over here.
        echo "<tr>
        <td width="110" bgcolor="$row_color" nowrap>
        $article_date</td>
        <td bgcolor="$row_color">
        <a href="articles.php?cmd=full_article&article_id=$article_id">$article_title</a></td>
        </tr>";
        // Add 1 to the row count
        $row_count++;
    }
    // Close out your table.
    echo "</table>";

    Ok, let's break this down.

    Code Breakdown

    Let's define what we have done here to give you a better understanding.

    Start the Table
     
    // Begin your table outside of the array
    echo "<table width="100%" border="0"
    cellpadding="4" cellspacing="0"><tr>
    <td width="110"><b>Event Date</b></td>
    <td><b>Event Title</b></td></tr>";

     
    I mentioned above that you want to start your table outside of the loop or array that you are going to display your data. The reason for this, as any experienced PHP developer may know, is so you can loop the rows and not the tables. Either way is fine, but for the course of this tutorial and my own coding methods, I use this way of doing things. This particular table will look something like below. I put a border size of 1 on my table just to show you in my example the borders. In my code I do not use borders unless absolutely necessary.

    Event Date Event Title

    Define The Color Variables

    // Define your colors for the alternating rows
        $color1 = "#CCFFCC"; 
        $color2 = "#BFD8BC"; 
        $row_count = 0;

     
    This is pretty straight forward. We are defining the colors that we decided to use and then setting the initial $row_count variable to 0. Later on we will add 1 to the row_count for every number of rows we find in the database.

    Do the MySQL Query

    // Perform an statndard SQL query:
    $sql_events = mysql_query("SELECT date_format(event_date, '%M %d, %Y') as event_date,
    event_title FROM my_events ORDER BY event_date ASC") or die (mysql_error());

     
    We won't teach you how to do an SQL query in this tutorial. You should already know how to do that if are trying to alternate your rows. However, in this SQL statement, we are pulling from two coloumns in our table. event_date and event_title for each of the events in our database will be displayed in our table rows below.

    Use the SQL Query

    // We are going to use the "$row" method for this query. This is just my preference.
    while ($row = mysql_fetch_array($sql_events)) {
        $event_date = $row["event_date"];
        $event_title = $row["event_title"];

     
    There are quite a few ways that you can use the $sql_events variable we defined in the previous step. For this tutorial and my methods of coding, I use this one here. All we are doing is fetching an array from the $sql_events and defining the results as variables to be used later.

    Equation

    $row_color = ($row_count % 2) ? $color1 : $color2;
     
    In order for this to work properly, we must perform this small equation which is going to decide which color to use in which row of our table. I am almost positive if you add another color varialbe like "$color3" above and you change the $row_count % 2 to $row_count % 3 and then add your third color variable here that you can get 3 colors of alternating rows. I have not tested that yet, so if it works, let me know!

    Define Your Rows

    // Echo your table row and table data that you want to be looped over and over here.
    echo "<tr>
    <td width="110" bgcolor="$row_color" nowrap>
    $article_date</td>
    <td bgcolor="$row_color"><a href="articles.php?cmd=full_article&article_id=$article_id">$article_title</a></td>
    </tr>";
     

    Here you are going to define your rows and table data. Take special note that I have defined the td bgcolor to $row_color. This is required, or this whole thing will not work!

    Add 1 to the Count!

    // Add 1 to the row count
    $row_count++;

    To get your rows to alternate color, you must add 1 to the count. This is the same as saying $row_count +1;

    Close out the Table!

    }
    // Close out your table.
        echo "</table>";

     
    You must end your array with } and then close out the table html tag. That's it you're done!

    Let's see the results

    The Results

    Ok, we've done all of this code and hopefully when we run this script it will work. If you have everything setup correctly, you should be in there. Here's the results that I got from my database query:

    Event DateEvent Title
    May 18, 2002Town Festival
    March 05, 2002Air Show
    March 04, 2002River Cruise
    March 03, 2002City Parade

    That's about it! Now hopefully you should be able to write your own code using alternating row colors!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More PHP Articles
    More By Eric 'phpfreak' Rosebrock

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Tester for SOA Quality V7.0.1

    Get a free trial download of the latest version of IBM Rational Tester for SOA Quality V7.0.1, a functional and regression testing tool that enables the creation, comprehension, modification and execution of testing GUI-less Web services.
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    PHP ARTICLES

    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP
    - PHP Frontend to ImageMagick
    - Using PEAR's mimeDecode Module
    - Incoming Mail and PHP







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 10 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek