Home > Enterprise >  PHP row background color even/odd
PHP row background color even/odd

Time:11-22

i have a static table(the ID is incremented through a loop and the rest are just repeated), I want to change the background of the even rows to red and odd rows to blue. i want to to do it with for and if. MY CODE:

<html>
<head>
    <title></title>
</head>
<body>

<table>
    <tr>
        <th>id</th>
        <th>serial</th>
        <th>pds_number</th>
        <th>name</th>
        <th>familySize</th>
        <th>voucher_Value</th>
        <th>phone</th>
    </tr>
    
    <?php 
for ($i=1; $i <12 ; $i  ) { 
  if($i%2==0) {
     echo '<tr bgcolor="red"><td></td></tr>';
    }
    else {
echo '<tr bgcolor="blue"><td></td></tr>';

    }  
     
    ?>
  
   <tr>
    <td> <?php echo "$i"; ?></td>
        <td> <?php echo "a001" ?></td>
            <td> <?php echo "1234"; ?></td>
                <td> <?php echo "nn"; ?></td>
                    <td> <?php echo "1"; ?></td>
                        <td> <?php echo "100"; ?></td>
                            <td> <?php echo "077011111"; ?></td>
   </tr>

<?php  } ?>

</table>
</body>
</html>```

CodePudding user response:

This is better solved in CSS, like this:

<style>
  table tr:nth-child(even) td {
    background-color: red;
  }
  table tr:nth-child(odd) td {
    background-color: blue;
  }
</style>

CodePudding user response:

Try like this:

<html>
<head>
    <title></title>
</head>
<body>

<table>
    <tr>
        <th>id</th>
        <th>serial</th>
        <th>pds_number</th>
        <th>name</th>
        <th>familySize</th>
        <th>voucher_Value</th>
        <th>phone</th>
    </tr>
    
    <?php 
for ($i=1; $i <12 ; $i  ) { 
  if($i%2==0) {
     echo '<tr style="background-color:red;"><td></td></tr>';
    }
    else {
echo '<tr style="background-color:blue;"><td></td></tr>';

    }  
     
    ?>
  
   <tr>
    <td> <?php echo "$i"; ?></td>
        <td> <?php echo "a001" ?></td>
            <td> <?php echo "1234"; ?></td>
                <td> <?php echo "nn"; ?></td>
                    <td> <?php echo "1"; ?></td>
                        <td> <?php echo "100"; ?></td>
                            <td> <?php echo "077011111"; ?></td>
   </tr>

<?php  } ?>

</table>
</body>
</html>```
  •  Tags:  
  • php
  • Related