Styling loops with CSS

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Alcaeus
Forum Newbie
Posts: 2
Joined: Thu Nov 17, 2011 1:07 pm

Styling loops with CSS

Post by Alcaeus »

Hello all! :D

I'm a PHP noob and I have a question regarding mixing PHP with HTML and CSS. I'm sure this is really obvious, but I haven't been able to find out anything on Google. How would I style each line that is output from this while loop separately? For example, the first line that is output reads "John is 24 and lives in London" and I want this text to be red, but the second line reads "Lucy is 34 and lives in Manchester" and I want this text to be blue, and so on through 11 different MySQL rows.

Code: Select all

$query = "SELECT * FROM new_table";

$result = mysql_query($query);

while ($row=mysql_fetch_array($result)) {
echo $row['name'] . " is " . $row['age'] . " and lives in " . $row['location'] . "<br />";
I hope this is clear enough! :oops:

Many thanks! :P
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Styling loops with CSS

Post by Celauran »

Depends a little on what/how much logic you want to apply. In your example, what determines which colour the line should be? If you just want alternating light and dark rows, for example, you could just place a counter inside your loop and set the class depending on whether the current value of the counter is even or odd.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Styling loops with CSS

Post by pickle »

To further expound on what ~Celauran said - you want something like this pseudo-code:

Code: Select all

$zebra = false;
while(looping through your rows)
{
  $css_class_for_row = ($zebra) ? "blue" : "red";
  $zebra = !$zebra;
}
if($even_or_odd
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply