I was wondering if there was a way to alter the color of every other row in the list output by my php code. Please note that this code is all within a table, I just didn't include everything... // Create the query $query = "SELECT date, stock, profit FROM recent ORDER by id DESC LIMIT 0,10"; // Send the query to MySQL $result = $mysqli->query($query, MYSQLI_STORE_RESULT); // Iterate through the result set while(list($date, $stock, $profit) = $result->fetch_row()) printf("<tr><td>%s</td> <td align=\"center\">%s</td> <td align=\"right\">%s</td> </tr>", $date, $stock, $profit); PHP: I know I can easily edit ALL the rows, but am not quite sure how to edit every other one! Help would be appreciated.
Theres a few ways you can do it, probably the simplest is; // Iterate through the result set $rowcol = "#FFFFFF"; while(list($date, $stock, $profit) = $result->fetch_row()) { print "<tr><td style=\"background-color: $rowcol;\">$date</td> <td align=\"center\" style=\"background-color: $rowcol;\">$stock</td> <td align=\"right\" style=\"background-color: $rowcol;\">$profit</td> </tr>\n"; if($rowcol == "#FFFFFF") $rowcol = "#AAAAAA"; else $rowcol = "#FFFFFF"; } PHP: You can assign the color to a CSS class or such too, but you get the idea.....
Could you explain how the code will work? I don't really understand what's going on with it. Just want to make sure that I actually know why I add that.
Sure - see the comments below.... #First assign a default color - it will be used on the first row, otherwise its "not set" $rowcol = "#FFFFFF"; while(list($date, $stock, $profit) = $result->fetch_row()) { # print out the table row, using the current row color (first row = white) print "<tr><td style=\"background-color: $rowcol;\">$date</td> <td align=\"center\" style=\"background-color: $rowcol;\">$stock</td> <td align=\"right\" style=\"background-color: $rowcol;\">$profit</td> </tr>\n"; # if the current row color is white, make it grey, since a white row has just been output if($rowcol == "#FFFFFF") $rowcol = "#AAAAAA"; # otherwise, it has to be grey, so set it back to white as a grey row has just been output else $rowcol = "#FFFFFF"; } PHP: Essentially, you are just setting a "flag" - on every iteration of the loop you set it to one, or the other, depending on the color just used