-1

The following code can make a table with colored using two colors alternatively:

$num = mysql_num_rows($qPhysician);
$i=0;
echo "<table>"
while($i < $num)

{
if ($i % 2 == 0){
echo "<tr class='style1'>";
}
else{
echo "<tr class='style2'>";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";

echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";

echo "</tr>";

$i++;

}
echo "</table>";

Suppose I have multiple colors. red, green, yellow, blue etc. Is there any way to make a table colored using these colors alternatively? How will I do that?

  • 3
    why don't you just use CSS for this with `:nth`? – Funk Forty Niner Aug 10 '18 at 19:32
  • [W3schools](https://www.w3schools.com/cssref/sel_nth-child.asp) has a good article about how to accomplish this with CSS. – Evan Edwards Aug 10 '18 at 19:34
  • 1
    ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Aug 10 '18 at 19:34

2 Answers2

1

Hi user10179141 try this code css and html.

table tr:nth-child(2n) {
    background-color: #4a94ed;
    border-color: #4a64ed;
}
<table>
  <tr>
    <td>Col 1</td>
    <td>Col 2 </td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2 </td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2 </td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2 </td>
  </tr>
</table>

Definition and Usage

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.

n can be a number, a keyword, or a formula.

Example a situation, i need select a second paragraph in text.

i use p:nth-child(2) {css propertys}

https://codepen.io/pauloserafimtavares/pen/gjqrYQ

W3C More informations for CSS Selector https://www.w3schools.com/cssref/sel_nth-child.asp

0

You could use something like the following to alternate the colour every row (for four colours.)

<style> 
tr:nth-child(4n+1) {
    background: red;
}
tr:nth-child(4n+2) {
    background: green;
    }

tr:nth-child(4n+3) {
    background: yellow;
}
tr:nth-child(4n+4) {
    background: blue;
}

</style>
Evan Edwards
  • 182
  • 11