Page 1 of 1

Styling loops with CSS

Posted: Thu Nov 17, 2011 2:05 pm
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

Re: Styling loops with CSS

Posted: Thu Nov 17, 2011 2:11 pm
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.

Re: Styling loops with CSS

Posted: Thu Nov 17, 2011 3:19 pm
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