Skip to content Skip to sidebar Skip to footer

Change Color Of Table Based On Values From Sql Query Database Using Php

I have some code to produce a table from an SQL query. I would like the background color of the cell to represent the value of 'rel.cat', which can be an integer between 1-8.

Solution 1:

your if statements should have a double "==".

Instead of

if ($catc = "1")

it should be

if ($catc == "1")

Assign == everywhere in all your if conditions.

And also assign the parameter to the function.

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    $id = $row["id"];
    $catc = $row["colourcode"];
    echo"<tr>";
    echo"<td>$id</td>";
    echo"<td bgcolor='getcolour(\"$catc\")'>$catc</td>";
    echo"</tr>";
}

Get the parameter in the function as well.

functiongetcolour($catc)
{

Solution 2:

You have several problems.

  • Pass and accept $catc to the function getcolour().
  • Use logical operator (==) not assignment (=) in your conditions.
  • Properly output the function results.

Code:

functiongetcolour($catc) {
    // ... existing code
}

echo"<td bgcolor='" . getcolour($catc) . "'>$catc</td>";

Solution 3:

Supply the variable $catc to your function. i.e.

functiongetcolour($catc) {
    // ... existing code
}

echo"<td bgcolor='getcolour($catc)'>$catc</td>";

You might find it more readable to use a switch() instead

function getcolour($catc) {
    switch($catc)
    {
        case 1:
            return'#000000';
            break;
        case 2:
            return'#C0C0C0';
            break;
        case 3:
            return'#00FF00';
            break;
        case 4:
            return'#0000FF';
            break;
        case 5:
            return'#FF99FF';
            break;
        case 6:
            return'#FF9900';
            break;
        case 7:
            return'#FF0000';
            break;
        default:
            return'#FFFFFF';
            break;
    }
}

echo '<td bgcolor="' . getcolour($catc) . '">' . $catc . '</td>';

Solution 4:

You're not passing a value to the getcolour function. That function will need to be changed too, at the moment the if statement assigns a value rather than comparing values, so the first if statement will always be true. Change each one to '==' rather than '='.

change this :

echo"<td bgcolor='getcolour()'>$catc</td>";

to this :

echo"<td bgcolor='".getcolour($row['catc'])."'>.$row['catc']</td>";

This assumes that catc is returned from the query as 'catc'.

Solution 5:

functiongetcolour($catc){
..........etc

and call it

<td bgcolor='",getcolour($catc),"'>$catc</td>

and don't forget bgcolor is deprecated =)

Post a Comment for "Change Color Of Table Based On Values From Sql Query Database Using Php"