Jump to content

need to assign css class to <td> tag


webguync

Recommended Posts

Hello,

 

I am extracting data into an HTML table and I would like to make one of the table rows alternate colors by assigning a variety of CSS classes, but I am not sure how to do that within the PHP code I am using below:

 

any suggestions?

 

 

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

$fields_num = mysql_num_fields($result);

echo "<h1>JBossworld 2008 Agenda: {$table}</h1>";
echo "<table border='1'><tr id='headers'>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

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

Link to comment
Share on other sites

Not sure if this is the 'correct' way but I would do something like:

 

 

inside of your loop put this:

 

 

$tdcolor = $tdcolor +1;
if ($tdcolor % 2 == 0 ){
  echo "<td class='even'>";
} else {
  echo "<td class='odd'>";
}

 

The if tdcolor %2 is an odd or even script, so if it is even it will show one color - odd the other.

 

Link to comment
Share on other sites

<?php
$tdcolor = $tdcolor +1;
if ($tdcolor % 2 == 0 ){
  echo "<td class='even'>";
} else {
  echo "<td class='odd'>";
}
?>

 

...can be shortened to:

 

<?php
$tdcolor += 1;
echo($tdcolor % 2 == 0) ? '<td class="even">' : '<td class="odd">';
?>

 

Sorry to thread highjack but I tried your modified version of the code I wrote and it worked great.  I don't understand though the ? and the :  .  Could you explain that as if I was a two year old?  What I mean is the logic behind it.....

 

  I'm thinking the ? means if true do something : <--- (if false) something else and I'll also assume the +=1 then is the same as $whatever = $whatever + 1;  Am I correct in my assumptions?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.