I display the information of MySQL table in web, it's easy but I want to change the background color of a cell when it has certain value. In the example, my table has different fields: id, nombre, apellido1, apellido2, curso, e-mail, and direccion. I want to get that when the field curso = primero, the color of that cell was red.
<?php
$connect = mysql_connect("localhost", "root", "") ;
if (!$connect) {
die ("Can not connect: " . mysql_error () ) ;
}
mysql_select_db("modelobdclase", $connect) ;
$sql = "SELECT * FROM datosalumnado";
$myData = mysql_query($sql, $connect) ;
echo "<table border=1>
<tr>
<th> id_alumnado </th>
<th> nombre </th>
<th> apellido1 </th>
<th> apellido2 </th>
<th> curso </th>
<th> fechadenacimiento </th>
<th> e-mail </th>
<th> direccion </th>
</tr>";
[B]
$valor= "primero";
function dame_color($valor) {
if ($valor == 'primero') return 'red';
else ' ';
}
while ($record = mysql_fetch_array ($myData)) {
$color = dame_color($row->[B] 'curso' );
[B]echo "<td bgcolor=$color>";
echo "<tr>";
echo "<td>" . $record ['id_alumnado'] . "</td>";
echo "<td>" . $record ['nombre'] . "</td>";
echo "<td>" . $record ['apellido1'] . "</td>";
echo "<td>" . $record ['apellido2'] . "</td>";
echo "<td>" . $record ['curso'] . "</td>";
echo "<td>" . $record ['fechanacimiento'] . "</td>";
echo "<td>" . $record ['e-mail'] . "</td>";
echo "<td>" . $record ['direccion'] . "</td>";
}
echo "</table>" ;
mysql_close($connect) ;
?>
Try this
$color = ($record ['curso'] == 'primero') ? "style='background-color:#f00;'" : '';
echo "<td $color>" . $record ['curso'] . "</td>";
Thanks user 36.... it was a fantastic answer. It works!!
The complete code would be:
function dame_color($valor) {
if ($valor == 'primero') return 'red';
else return 'white';
}
while ($record = mysql_fetch_array ($myData)) {
$color = ($record ['curso'] == 'primero') ? "style='background-color:#f00;'" : '';
echo "<tr >";
echo "<td>" . $record ['id_alumnado'] . "</td>";
echo "<td>" . $record ['nombre'] . "</td>";
echo "<td>" . $record ['apellido1'] . "</td>";
echo "<td>" . $record ['apellido2'] . "</td>";
echo "<td $color>" . $record ['curso'] . "</td>";
echo "<td>" . $record ['fechanacimiento'] . "</td>";
echo "<td>" . $record ['e-mail'] . "</td>";
echo "<td>" . $record ['direccion'] . "</td></tr>";
}
echo "</table>" ;