Reputation: 43
I am new to PHP and I want to display a table from my database with each row with a different color from other rows and I tried answers and solutions similar to my question but I failed to make it done on the rows of <td><?= $field ?></td>
This my script :
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost','root','','class');
$mysqli->query("set names 'UTF8'");
$data = [];
$res = $mysqli->query("SELECT math, physics, english FROM student order by math desc");
while ($row = $res->fetch_assoc()) {
foreach(array_keys($row) as $key) {
$data[$key][] = $row[$key];
}
}
?>
<div>student</div>
<table border="1">
<?php foreach($data as $key => $val): ?>
<tr>
<td><?= $key ?></td>
<?php foreach($val as $field): ?>
<td><?= $field ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
Upvotes: 0
Views: 337
Reputation: 832
You can do this with the help of CSS
For even and odd selectors you follow following syntax
table tr:nth-child(even) td{
background: #f1f1f1;
}
table tr:nth-child(odd) td{
background: #fff;
}
Upvotes: 1
Reputation: 128
I'm just using the following function as an example which returns a random color. The function has been posted by @outis
function rand_color() {
return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}
This will return a random RGB hex string which you can use in your foreach loop, like this (note the <tr>
tag):
<div>student</div>
<table border="1">
<?php foreach($data as $key => $val): ?>
echo '<tr style="background-color:' . rand_color() . '">';
<td><?= $key ?></td>
<?php foreach($val as $field): ?>
<td><?= $field ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
</div>
If you just want to use specifiek colors, then i suggest to define those colors in an array, and then use those as you loop through your data.
Upvotes: 0