BarclayVision
BarclayVision

Reputation: 863

Bootstrap alternating row color in dynamically created table

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;
    }

Upvotes: 3

Views: 3229

Answers (2)

Armin
Armin

Reputation: 1178

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>"; 

Upvotes: 3

Hewlett
Hewlett

Reputation: 161

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

Upvotes: 0

Related Questions