Alternating row color in mysql output
Moderator: General Moderators
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Wants to be something like:aussie_clint wrote:ok, its out putting it into a table now, but all in one colum
eg
row1
row2
row3
row1
row2
row3
Code: Select all
<?PHP //connect to the mysql database $connection=mysql_connect("localhost","computer_test","test1"); mysql_select_db("computer_price",$connection); $query="SELECT p.PartNumber, p.Description, (p.IncTax*1.3) AS Price FROM `price list` p"; $data_resource=mysql_query($query,$connection); $row1 = "#cfdafg"; $row2 = "#ff0000"; $rowcolor = $row1; //Defining HTML table $table="<table cellspacing=0 cellpadding=0 border=1 width=400>"; while ($row = mysql_fetch_array($data_resource)) { $table.=sprintf('<tr bgcolor="%s"><td>'.$row['PartNumber'].'</td></tr>', $rowcolor); $table.=sprintf('<tr bgcolor="%s"><td>'.$row['Description'].'</td></tr>', $rowcolor); $table.=sprintf('<tr bgcolor="%s"><td>'.$row['Price'].'</td></tr>', $rowcolor); if ($rowcolor == $row1) $rowcolor = $row2; if ($rowcolor == $row2) $rowcolor = $row1; } //Closing HTML table $table.="</table>"; //Displying table and closing mysql database if not need echo $table; mysql_close(); ?>
Code: Select all
$table="<table cellspacing=0 cellpadding=0 border=1 width=400>";
while ($row = mysql_fetch_array($data_resource)) {
$table.=sprintf('<tr bgcolor="%s"><td>'.$row['PartNumber'].'</td>', $rowcolor);
$table.='<td>'.$row['Description'].'</td>';
$table.='<td>'.$row['Price'].'</td></tr>';
if ($rowcolor == $row1) $rowcolor = $row2;
if ($rowcolor == $row2) $rowcolor = $row1;
}
//Closing HTML table
$table.="</table>";Code: Select all
$rowcount = 0;
$table="<table cellspacing=0 cellpadding=0 border=1 width=400>";
while ($row = mysql_fetch_array($data_resource)) {
$rowcount++;
// if the rowcount is even, use #cfdafg, else use #ff0000
$rowcolor = $rowcount % 2 == 0 ? "#cfdafg" : "#ff0000";
$table.="<tr bgcolor="$rowcolor"><td>".$row['PartNumber']."</td>";
$table.="<td>".$row['Description']."</td>";
$table.="<td>".$row['Price']."</td></tr>";
}
//Closing HTML table
$table.="</table>";EDIT: Tidied up the code a little bit, and added comments
-
aussie_clint
- Forum Commoner
- Posts: 41
- Joined: Mon Jul 31, 2006 9:14 am
- Location: Brisbane, Australia
- Contact: