开发者

How do i change the html element dynamically while iterating from database

I am using a table to iterate the data from the database in a table. my html code is

    <table id="tablesorter"> 
        <thead> 
           <tr> 
           <th>Name</th> 
           <th>Location</th> 
           <th>Email<开发者_开发技巧;/th> 
           <th>Phone</th> 
           </tr> 
        </thead> 
        <tbody> 
           <tr> 
           <td>Your Name</td> 
           <td>Somewhere</td> 
           <td>test@test.com</td> 
           <td>9999999999</td> 
           </tr> 
        <tr class="trow"> 
           <td>Your Name</td> 
           <td>Somewhere</td> 
           <td>test@test.com</td> 
           <td>9999999999</td>  
           </tr> 
           </tbody> 
   </table>

In my HTML table i am using a class for a table row to style it for every second table row. now while fetching the data from the database i want to make sure it does the same thing. it should add the class trow for every second table row.

what would be the logic behind this using with while loop?


Basically, this is what you want to do:

  1. Use a counter variable to keep track of the row you're at
  2. On each row, check if the row counter is even. The easiest way to do this is with the modulo operator %.

    6 % 2 == 0 // true
    5 % 2 == 1 // true
    4 % 2 == 1 // false
    


Seems to me that you could just use a ternary statement to set and unset the class variable as it loops through printing each row:

$class = ($class=='trow')?'':'trow';
<tr class="<?= $class ?>"> 
<td>Your Name</td> 
<td>Somewhere</td> 
<td>test@test.com</td> 
<td>9999999999</td> 
</tr> 

So that each time a row is printed the $class variable would toggle between trow and nothing.

I use this logic when creating lists that export to excel quite often


You'd use a simple state machine:

$evens = FALSE;
while($row = fetch_from_db()) {
     $evens = !$evens; // invert the even/odd flag
     $rowtype = ($evens === TRUE) ? ' class="trow"' : '';
     echo <<<EOL
<tr{$rowtype}>
   <td>etc...
</tr>

EOL;
}

Since $evens starts out false, on the first row it's inverted to true, which sets $rowtype to 'trow'. On the second row, it's inverted back to false, $rowtype becomes empty. On the 3rd row, we're back to true/trow, and so on, ping-ponging back and forth.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜