Table that changes color

Asked

Viewed 61 times

0

Good afternoon everyone, I am beginner in php would like to know how to change the color of a table that receives the database information. For example I have a technical intervention form where I have the status pending and completed, I want that when the status column get completed it turns green and if received pending would turn red, follow the code:

<?php
    require_once("conexao.php");
    $comando = "SELECT * FROM fit";
    $enviar=mysqli_query($conn, $comando);
    $resultado = mysqli_fetch_all($enviar, MYSQLI_ASSOC);
?>


<style>
    table, th, td {
      border: 2px solid black;
      border-collapse: collapse;
    }
    th, td {
      padding: 20px;
      text-align: left;
    }

    table, tr:nth-child(odd) {
    background-color: #eee;
    }

</style>

<div class="table" style="width:100%">
    <table>
    <tr>
        <th>id</th>
        <th>Técnico</th>
        <th>Estação</th>
        <th>Status</th>
    </tr>

<?php
    foreach ($resultado as $fit) {
        $id=$fit['id'];
        $tecnico=$fit['tecnico'];
        $estacao=$fit['estacao'];
        $status=$fit['situacao'];

?>
    <tr>
        <td><?=$id?></td>
        <td><?=$tecnico?></td>
        <td><?=$estacao?></td>
        <td><?=$status?></td>
    </tr>
<?php
}
?>
</table>
</div>

inserir a descrição da imagem aqui

1 answer

1

First, create a class in your CSS to style each status of your record:

td.pendente {
    background-color: red;
}
td.concluido {
    background-color: green;
}

Now, just add this style to the column as the status of the registration in question:

//...
<tr>
    <td><?=$id?></td>
    <td><?=$tecnico?></td>
    <td><?=$estacao?></td>
    <td class="<?= ($status == 'concluido' ? 'concluido' : 'pendente'); ?>"><?=$status?></td>
</tr>
//...

In that first 'concluido' in $status == 'concluido' will be made a comparison with what will come of your query. Soon, adjust as your records.

If in doubt about the operator ?:, I’ll leave a link that explains exactly how to use.

Recommended reading: PHP - Ternary operator

  • Thank you very much for your reply. How would it be if I wanted the entire completed row to be green and red pendant, not only the column as I had said in the case the whole row

  • @Vinicius first seeks to understand the solution proposed in my reply. Note that I have styled a column (td). If you want to style the entire line, take this styling to the line (tr). If you still have difficulty, comment here that I will supplement the answer.

  • Thank you so much for your help, I got what I wanted. Big hug.

Browser other questions tagged

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