简体   繁体   中英

How to display different color in html retrived from database?

I have 15 or more rows in mysql database. I want to retrieve them and display in 2 different colors.

For First row <tr><td height="30" bgcolor="#F5F5F5">....</td></tr>
For second row <td height="30" align="center" bgcolor="#FFFFFF">....</td></tr>
For third row <td height="30" bgcolor="#F5F5F5">....</td></tr>
For Forth row <td height="30" align="center" bgcolor="#FFFFFF">....</td></tr>
And so on....

How to display them in such order using php

You can use CSS selectors:

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

Sample: http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_nth-child_odd_even

You first need to fetch rows from database in your php script and then in php you can loop these rows and apply an odd or even class, I have made an example script using php array. In your case $items will contain rows fetched from DB.

$items = array("abc", "123", "def", "345", 'wer'); 
foreach($items as $key => $val) {
    if($key == 0 ) {
        $class = 'odd';
    }
    elseif($key%2 == 0) {
        $class = 'odd';     
    }
    else {
        $class = 'even';    
    }

    echo $class . " $val" ."<br/>";
}

Let me know if it help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM