3

Looking in Stack Overflow I found alternating row color. While this seems to work on a static table, my results is that all rows are pink. I cannot get it to work on a PHP dynamically created table with bootstrap:

$mdbFile = "\myAccessDatabase.mdb";
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$mdbFile", "", "");
$query = $pdo->prepare("SELECT * FROM Table");  
$query->execute();

echo "<table class='table table-striped table-bordered table-hover table-condensed table-responsive'>";                 
echo "<thead><tr>";
echo "<th>Last</th><th>First</th><th>XXX</th><th>YYY</th><th>ZZZ</th><th>WWW</th>";
echo "</tr></thead>";

for($i=0; $row = $query->fetch(); $i++){
    echo '<tbody><tr>';
    //echo "<th scope='row'>1</th>";
    echo "<td>".$row['LAST']."</td>";
    echo "<td>".$row['FIRST']."</td>";
    echo "<td>".$row['XXX']."</td>";
    echo "<td>".$row['YYY']."</td>";
    echo "<td>".$row['ZZZ']."</td>";
    echo "<td>".$row['WWW']."</td>";
}
echo "</tr></tbody></table>"; 

unset($pdo);
unset($query);

CSS:

.table-striped>tbody>tr:nth-child(odd)>td,
    .table-striped>tbody>tr:nth-child(odd)>th {
        background-color: pink;
    }
Community
  • 1
  • 1
BarclayVision
  • 865
  • 2
  • 12
  • 41
  • I wish more people spent as much time trying to resolve the question as they do editing the content of the question. While I agree the grammar and format is important, an unresolved question is still UNRESOLVED even with correct formatting. – BarclayVision Feb 23 '17 at 20:14
  • There is **table-striped** class already available for this, as early as Bootstrap 3. – andreszs Sep 08 '21 at 14:18

2 Answers2

3

Problem is probably that your opening tbody tag is inside a loop. So each row is treated as a frist one. Try taking it outside:

 echo '<tbody>';
for($i=0; $row = $query->fetch(); $i++){
    echo '<tr>';
    //echo "<th scope='row'>1</th>";
    echo "<td>".$row['LAST']."</td>";
    echo "<td>".$row['FIRST']."</td>";
    echo "<td>".$row['XXX']."</td>";
    echo "<td>".$row['YYY']."</td>";
    echo "<td>".$row['ZZZ']."</td>";
    echo "<td>".$row['WWW']."</td>";
    echo '</tr>';
  }
    echo "</tbody></table>"; 
Armin
  • 1,158
  • 1
  • 7
  • 16
  • thanks that did the trick - didn't think about the `` repeating. – BarclayVision Feb 23 '17 at 15:31
  • Don't forget your `tr` tag. Both opening and closing tags should be inside, or outside of the loop. I suppose you want it inside, so move your closing one inside the loop. – Armin Feb 23 '17 at 15:32
0

Try this .table-striped>tbody>tr:nth-of-type(odd) { background-color: pink; }

Hewlett
  • 161
  • 11