0

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>[email protected]</td> 
           <td>9999999999</td> 
           </tr> 
        <tr class="trow"> 
           <td>Your Name</td> 
           <td>Somewhere</td> 
           <td>[email protected]</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?

3 Answers 3

2

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
    
Sign up to request clarification or add additional context in comments.

Comments

1

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>[email protected]</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

2 Comments

wow so simple and easy to understand logic, that was brilliant answer and just the kind of solution i was looking for. thank you very much. :)
No problem, Ibrahim. The ternary has become by best friend of late
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.