How to change the table line color(php) according to the value?

Asked

Viewed 2,075 times

-2

<?php 
include_once("func/functions.php"); // Chama o arquivo de funções

function diaria($codmot,$periodo)
{
	$data =  (explode(" - ",$periodo));
	$datIni =  date('Y-m-d',strtotime($data[0]));
	$datFin =  date('Y-m-d',strtotime($data[1]));

	$conn_datapar = connect();
	$sql = "SP_TI_DIARIAS_E_LANCHES $codmot,'$datIni 00:00:00', '$datFin 23:59:59', 117";
	$stmt = sqlsrv_query($conn_datapar, $sql);	

	while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
	{
		$ficha = $row["CODFIC"];
		$data = $row["DATREF"]->format('d-m-Y H:i');
		$obs = $row["OBSERV"];
		$valor = $row["VLRADI"];

		echo "
			<tbody>
				<tr>
					<td>".$ficha."</td>
					<td>".$data."</td>
					<td>".$obs."</td>
					<td>R$".$valor."</td>
				</tr>
			</tbody>
		";
	}
}

Good afternoon, you guys! I really need your help. I have a table(php),filled with BD information,need these results,when the value of . $value. If it’s negative, the line turns red, when it’s positive, turn green. OBS: I used the grid, Does anyone know how to help me ? Thank you for your attention.

  • 4

    You can post the PHP code that generates the table?

  • I’ve been racking my brain with this for two days

  • If the answer solved your problem be sure to mark it as accepted. See https://i.stack.Imgur.com/evLUR.png and posrque https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

1 answer

1

Inside the while make a if else to set the color depending on the variable value $valor and place in the table row <tr style='background-color:".$color."'>

$valor = $row["VLRADI"];
// decide a cor do fundo das linhas
if($valor>0){
  $color="green";
}else{
  $color="red";
}

    echo "
        <tbody>
            <tr style='background-color:".$color."'>
                <td>".$ficha."</td>
                <td>".$data."</td>
                <td>".$obs."</td>
                <td>R$".$valor."</td>
            </tr>
        </tbody>
    ";

Nothing stops using CSS classes

CSS

  .verde{
     background-color:green;
  }

  .vermelha{
     background-color:red;
  }

PHP

$valor = $row["VLRADI"];

if($valor>0){
  $class="verde";
}else{
  $class="vermelha";
}

    echo "
        <tbody>
            <tr class='".$class."'>
                <td>".$ficha."</td>
                <td>".$data."</td>
                <td>".$obs."</td>
                <td>R$".$valor."</td>
            </tr>
        </tbody>
    ";
  • Thank you so much!! You showed me the error, I was putting the class in td instead of tr. Valew even by force.

Browser other questions tagged

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