1

Possible Duplicate:
How to set alternate row color for an iterated table in php?
Using CSS :even and :odd pseudo-classes with list items

I have a html table populated with data from a mysql table. I use the following code:

$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<tr>";

echo "</tr>\n";

while($row = mysql_fetch_row($result))
{
echo "<tr>";

foreach($row as $cell)
    echo "<td>$cell</td>";

echo "</tr>\n";
}
mysql_free_result($result);

Note: I normally use PDO statments but for this example i use mysql.

The code generate the table correctly. The question is: I want to apply a CSS to every second row with the following class=table_higlight. How can I do this?

1
  • :even and :odd have a poor browser compatibility... Commented Sep 3, 2012 at 17:02

2 Answers 2

5

Use:

$i = 0;
while($row = mysql_fetch_row($result)) {
  if ($i % 2 == 0 )
    echo '<tr class="even">';
  else
    echo '<tr class="odd">';

  foreach($row as $cell)
    echo "<td>$cell</td>";

  echo "</tr>\n";
  $i++
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why not just use css pseudo selectors eg. tr:odd or tr:even ?
1
while($row = mysql_fetch_row($result))
{
echo "<tr".(++$ctr%2 == 0 ? ' class="table_highlight"' : '').">";

foreach($row as $cell)
    echo "<td>$cell</td>";

echo "</tr>\n";
}

2 Comments

Why? foreach ($row as $cell) should list each column in the fetched row
No, the foreach is not useless. He is looping through all cells for the row. If you don't know the number of columns in the table, then you must loop through them all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.