tru
tru

Reputation: 117

How to echo different background colors in php

I am echoing data from my database in to an html table, is there a way I can make every other row a different background color similar to the color pattern of a balanced check book?

if ($serviceResults = $db->query("SELECT * FROM services WHERE technician_id = $userid ")){
    if($serviceResults->num_rows){
        while($row = $serviceResults->fetch_object()){
            $records[] = $row;
        }
        $serviceResults->free();
    }
}

if(!count($records)){
    echo "Please Add a Service";
} else {
?>
            <table>
                <thead>
                    <tr>
                        <th>Service Category</th>
                        <th>Service Name</th>
                        <th>Service Time</th>
                        <th>Service Cost</th>
                    </tr>
                </thead>
                <tbody>
                        <?php
                            foreach($records as $r){
                        ?>
                    <tr>
                        <td><?php echo escape($r->serviceCategory); ?></td>
                        <td><?php echo strtoupper(escape($r->serviceName)); ?></td>
                        <td><?php echo gmdate("H:i" , $r->serviceTime) . ' <b>Hr/Min</b>'; ?></td>
                        <td class="cost"><?php echo '$' . escape($r->serviceCost); ?></td>
                    </tr>
                    <?php
                    }
                    ?>
                </tbody>
            </table>
            <?php
            }
            ?>

I have 10 counts in my database at the moment and this echos the table great but I want every even rows say color gray and odd rows color white.. is this possible?

Upvotes: 0

Views: 169

Answers (1)

عثمان غني
عثمان غني

Reputation: 2708

You can add following css to the <style></style> element in the page.

tr:nth-child(even) {background: #666666}
tr:nth-child(odd) {background: #FFF}

See this for more information.

Hope it helps

Upvotes: 3

Related Questions