I have a table that get its rows from a MYSQL database
<table id="table1">
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_query("SET NAMES `utf8`"); // UTF 8 support!!
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr>
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
</table>
i have 2 css class called "A" and "B" for Odd Rows and Even Rows
i currently getting this done by replacing <tr>
with <tr class='<?php echo $row['Row'].""; ?>'>
and i have in my Database table a column "Row" which i add in A or B for even or odd row... the problem is if i wanna delete or add a new row between one of these i will have to change all the A and B in the other.
I have seen in another questions many way to do that in javascript or jquery but for a normal table with TR's which is not my case...(tried some of these scripts but couldn't get it fixed)
So what i want an easier way to do that Even and Odd rows, Thanks!
Why didn't you use modulo in your
while
loop ? It's a better way than store your class in your database... :There are many ways to do this, PHP, Javascript and even pure CSS. Here's the PHP way to add a class to every other row:
Basically the modulus operator returns the remainder of dividing the nubmers either side of it, so for example
3 % 2 == 1
,4 % 2 == 0
,5 % 2 == 1
, so we can tell if$i
is odd or even and alternate the classes added to the<tr>
.IMHO you want to either do it this way for 100% guarantee it will work (no browser dependencies) or if you design your app for modern browsers go for the CSS route.
You can add those classes using jQuery easily like this
do it in CSS way (no inline class) once and for all:
in CSS:
in your HTML:
thats it, no matter if your table rows are removed/or not.