mmdel
mmdel

Reputation: 1279

dynamically coloring <td>'s based on mysql retrieved values

I need to generate a simple table with dynamically coloured <td>'s based on mysql retrieved values.

Here is what I need:

$target = 20;
$achieved = 13;
echo "<table border='1'><tr>";
for($i = 0; $i <= $target; $i++){
echo "<td></td>";
}
echo "</tr></table>";

The above code plots a table with no of <td>'s equal to $target. All I need is then to color the background of these <td>'s with the value inside variable $achieved. So in this case I want 13 colored <td>'s.

Upvotes: 0

Views: 57

Answers (4)

miltos
miltos

Reputation: 1019

maybe you can try this, and add a td.coloured on your css

$target = 20;
$achieved = 13;
echo "<table border='1'><tr>";
for($i = 0; $i <= $target; $i++){
    if ($i < $achieved) {
        echo "<td class=\"coloured\"></td>";
    }
    else {
        echo "<td></td>";
    }
}
echo "</tr></table>";

Upvotes: 2

Burak Tokak
Burak Tokak

Reputation: 1850

I'm not sure if i understand well but i'll try.

$target = 20;
$achieved = 13;
echo "<table border='1'><tr>";
for($i = 0; $i <= $target; $i++){
if($i<=$archieved){
echo "<td bgcolor='red'></td>";
}else{
echo "<td></td>";
}
}
echo "</tr></table>";

Upvotes: 0

newfurniturey
newfurniturey

Reputation: 38416

You should be able to use a standard if statement here, something similar to:

if ($i < $achieved) // do the color

Inside the loop, you can populate a $bgcolor variable and then append that into the <td> you're outputting:

for($i = 0; $i <= $target; $i++){
    $bgcolor = '';
    if ($i < $achieved) {
        // give it a red background color
        $bgcolor = ' bgcolor="#ff0000"';
    }

    echo "<td" . $bgcolor . "></td>";
}

If you want more advanced styles, I'd suggest going with CSS instead of the bgcolor attribute. The same approach can be taken as above:

for($i = 0; $i <= $target; $i++){
    $style = '';
    if ($i < $achieved) {
        // give it a red background color
        $style = ' style="td-acheived"';
    }

    echo "<td" . $style . "></td>";
}

And then you could have the style:

<style>
    .td-acheived {
        background-color: #ff0000;
    }
</style>

Upvotes: 1

haxxxton
haxxxton

Reputation: 6442

i would do this by combining it with css with the following change to your php

$target = 20;
$achieved = 13;
echo "<table border='1'><tr>";
for($i = 0; $i <= $target; $i++){
echo "<td class='bgcolor-".$achieved."'></td>";
}
echo "</tr></table>";

then in your css file

.bgcolor-13{
    background-color:blue;
}

Upvotes: 0

Related Questions