PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

ALTERNATING ROW COLORS WITH PHP AND MYSQL - METHOD 2

This is another, slightly more complex method, showing you how to achieve alternate row colors when displaying records from a mysql database using PHP. A simpler method can be found here.

As with all your PHP programming, it is a good habit to put your database connection details in a separate file and then include it in your scripts when you need it. The open_db.php at the top of this script below is the database connectivity.

<?

include("open_db.php");

We then select our data out of the database.

$query = "SELECT keywords FROM google_search";
$result = mysql_query($query) or die(mysql_error());

We then get a count of the total number of rows of data we have.

$NumRows = mysql_num_rows($result);

We then echo the opening table structure as follows:

echo "<table cellpadding='0' cellspacing='0'>";

We now retrieve the results from our database using a for loop. :

for($i = 0; $i < $NumRows ; $i++)
{
$row = mysql_fetch_array($result);
$keywords=$row['keywords'];

If the row number $i is divisible by 2 with a remainder, then the color is red else it is yellow (change colors as per your requirement).

if($i % 2)
{
$RowColor="bgcolor='red'";
}
else
{
$RowColor="bgcolor='yellow'";
}

We now print our row assigning it the bgcolor from variable $RowColor and echo our data (which are keywords here).

echo "<tr ".$RowColor."><td>";
echo $keywords;
echo "</td></tr>";

We close the loop.

}

We close the table.

echo "</table>";

?>

The full script is below:

<?

include("open_db.php");

$query = "SELECT keywords FROM google_search";
$result = mysql_query($query) or die(mysql_error());

$NumRows = mysql_num_rows($result);

echo "<table cellpadding='0' cellspacing='0'>";

for($i = 0; $i < $NumRows ; $i++)
{
$row = mysql_fetch_array($result);
$keywords=$row['keywords'];

if($i % 2)
{
$RowColor="bgcolor='red'";
}
else
{
$RowColor="bgcolor='yellow'";
}

echo "<tr ".$RowColor."><td>";
echo $keywords;
echo "</td></tr>";

}

echo "</table>";

?>

A More Simple Method

Home | Privacy Policy | Terms Of Use | Contact Us