Change color of an html table field according to php database status condition

Asked

Viewed 677 times

1

In a table generated from database data, I need to change to certain colors of a <td></td> if the value of the field read in the database is as: 0 or 1. Example if the field read is in 0 the background <td></td> turns red, if you have 1 turns blue.

My code is like this:

require_once('class/Conexao.class.php');
                 $cnpj = $_SESSION['CNPJ'];
                    try {
                        $pdo = new Conexao(); 
                        $resultado = $pdo->select("SELECT protocolo,nomeBoleto,categoria,hr_dt_inserido,lido FROM boletos WHERE CNPJ='$cnpj' ORDER BY hr_dt_inserido DESC");
                        $pdo->desconectar();

                        }catch (PDOException $e){
                            echo $e->getMessage();
                        }   
                        //resgata os dados na tabela
                        if(count($resultado)){
                            foreach ($resultado as $res) {
    $msg .="                <tr>";
    $msg .="                    <td>".$res['protocolo']."</td>";
    $msg .="                    <td>".$res['nomeBoleto']."</td>";
    $msg .="                    <td>".$res['categoria']."</td>";
    $msg .="                    <th>".date('d/m/Y', strtotime($res["hr_dt_inserido"]))."</th>";
    $msg .= '               <td><a href="visualizar.php?protocolo=' . $res['protocolo'] . '" class="btn btn-primary" target="_blank">Visualizar</a></td>';
    $msg .= '               <td><a href="download.php?protocolo='. $res['protocolo'].'" class="btn btn-primary">Download</a></td>';
    $msg .="                </tr>";                            
                            }   
                        }else{
                            $msg = "";
                            $msg .="Nenhum resultado foi encontrado...";
                        }

1 answer

2


You can add a class to td ending with 0 or 1. For example:

"<td class='fundo". $res['campo que retorna 0 ou 1'] ."'>".$res['protocolo']."</td>";

And in CSS you create the style of the two classes, .fundo0 and .fundo1:

<style>
.fundo0{
   background-color: red; /* fundo vermelho */
}

.fundo1{
   background-color: blue; /* fundo azul */
}
</style>
  • It worked perfectly, thanks again!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.