使用PHP根据SQL Query数据库中的值更改表的颜色

fal*_*lcs 1 html php sql

我有一些代码来从SQL查询生成一个表.我希望单元格的背景颜色代表"rel.cat"的值,它可以是1-8之间的整数.

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// Connect to the database server
$dbcnx = mysql_connect("xxxxx",xxxxx,xxxxx);
if (!$dbcnx) {
  echo( "<P>Database Connection Failed</P>" );
  exit();
}
// Select the matrix databse database
  if ( !@mysql_select_db("sustaina_matrix") ) {
    echo( "<P>Not Connected to Matrix Database</P>" );
    exit();
  }
// Assign the query
$query = "SELECT rel.id, rel.cat colourcode FROM rel";
// Execute the query
$result = mysql_query($query);
if (!$result){
    die ("Could not query the database: <br />". mysql_error());
}
?>
<table>
    <tr>
        <th>Relationship ID</th>
        <th>Colour ID</th>
</tr>
<?php
// Change colours
function getcolour()
{
    if ($catc = "1")
        return '#000000';
    elseif($catc = "2")
        return '#C0C0C0';
    elseif($catc = "3")
        return '#00FF00';
    elseif($catc = "4")
        return '#0000FF';
    elseif($catc = "5")
        return '#FF99FF';
    elseif($catc = "6")
        return '#FF9900';
    elseif($catc = "7")
        return '#FF0000';
    else
        return '#FFFFFF';
}
// Fetch and display the results
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</td>";
    echo "</tr>";
}
?>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

目前所有细胞都是红色的,我不知道为什么.

Abh*_*aha 5

你的if语句应该有一个双"==".

代替

if ($catc = "1")
Run Code Online (Sandbox Code Playgroud)

它应该是

if ($catc == "1")
Run Code Online (Sandbox Code Playgroud)

在所有if条件中分配==无处不在.

并将参数分配给函数.

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>";
}
Run Code Online (Sandbox Code Playgroud)

获取函数中的参数.

function getcolour($catc)
{
Run Code Online (Sandbox Code Playgroud)