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 Date | Event Title |
| May 18, 2002 | Town Festival |
| March 05, 2002 | Air Show |
| March 04, 2002 | River Cruise |
| March 03, 2002 | City 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
developerWorks - FREE Tools! |
Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered! FREE! Go There Now!
|
|
|
|
Download a free trial version of IBM Rational Developer for System z, software that can help you deliver core development capabilities; the power of Java Platform, Enterprise Edition (Java EE); and rapid application development support to diverse enterprise application development teams. With comprehensive development tools to help create, deploy and maintain traditional enterprise and composite applications, Rational Developer for System z enables developers with different technical backgrounds to easily participate in important technology projects. FREE! Go There Now!
|
|
|
|
Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase. FREE! Go There Now!
|
|
|
|
As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change. FREE! Go There Now!
|
|
|
|
The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times. FREE! Go There Now!
|
|
|
|
Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base. FREE! Go There Now!
|
|
|
|
Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components. FREE! Go There Now!
|
|
|
|
This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product. FREE! Go There Now!
|
|
|
|
This whitepaper provides areas to consider when evaluating any software configuration management solution. It addresses how the IBM solutions (Rational ClearCase and Rational ClearQuest) meet the needs and requirements of both project leaders and developers to provide successful Software Change and Configuration Management. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |