PHP: Highlight every second row of table - php

I use this code to create a HTML table
for ($x = 0; $x <= $requiredRows; $x++) {
echo "<tr>";
echo "<td>";
echo someArrayStuff($x);
echo "</td>";
echo "<td>";
echo $someArrayStuff[$x][arrayinfos];
echo "</td>";
echo "<td>";
echo $someArrayStuff[$x][arrayinfos];
echo "</td>";
echo "</tr>";
}
Now I want to highlight every second row with a background color, how can I do this with PHP? I don't want to define it in the CSS file.
Thanks for all your help, now it works with this code:
if($x%2 == 0) { echo "<tr bgcolor='#FFFFF'>"; } else { echo "<tr bgcolor='#FFFFF'>"; }

if($x%2 == 0) {
echo '<tr class="bg-highlight">';
} else {
echo "<tr>";
}
and define a css class:
.bg-highlight {
background-color: red;
}

You can use mod. $x%2 will check if its a even row. which will be alternate row. If its found as even row then a different background color is given.
for ($x = 0; $x <= $requiredRows; $x++) {
if($x%2 == 0) { //even
echo "<tr style="background-color: #FF0000">";
} else { // odd
echo "<tr>";
}
echo "<td>";
echo someArrayStuff($x);
echo "</td>";
echo "<td>";
echo $someArrayStuff[$x][arrayinfos];
echo "</td>";
echo "<td>";
echo $someArrayStuff[$x][arrayinfos];
echo "</td>";
echo "</tr>";
}

You can simply create a dynamic class which will alter as per your loop
$class = ($x%2 == 0) ? "highlight" : "";
echo "<tr class='$class'>";
Just create a class named
.highlight{
background-color: grey;
}

Or You can simply use this code in css for odd or even rows of table.
div:nth-child(even)
{
background-color: yellow;
}

for ($x = 0; $x <= $requiredRows; $x++) {
echo "<tr";
if ($x % 2 === 1) {echo " style=\"background-color: yourFavoriteColor;\"";}
echo ">";
..................

Related

how to combine rows data of same id in one row

My controller function:
function index()
{
$data['user_clicks'] = $this->common_model->get_userClicks();
$this->load->view('common/header');
$this->load->view('content_pages/user_clicks',$data);
$this->load->view('common/footer');
}
My model
function get_userClicks()
{
$this->db->select('agent_id,click_type,click_count');
$this->db->select_sum('click_count');
$this->db->from('daily_clicks');
$this->db->group_by('click_type,agent_id');
$this->db->order_by('agent_id');
$q = $this->db->get();
return $q->result_array();
}
this is i am getting, what i want is to get the click_count of phone click, email click,offline click with respect to their columns and their total clicks is already done.
the data base image is the last one klindly help me get through it.
Thank you
Try this,
$resarr=count($resultarray);
<table>
<tr>
<th>Agent_id</th>
<th>phone_click</th>
<th>email_click</th>
<th>offline_click</th>
<th>total_click</th>
</tr>
for($i=1; $i<100; $i++){ //agent id
for($j=1; $j<=$resarr; $j++) //number of records
{
echo "<tr>";
if($arr['user_clicks'][$j]['agent_id'] == $i)
{
if(!empty($arr['user_clicks'][$j]['agent_id']){
echo "<td">
echo $arr['user_clicks'][$j]['agent_id'];
echo "</td>";
}
if($arr['user_clicks'][$j]['click_type']=='phone'){
echo "<td">
echo $arr['user_clicks'][$j]['click_type'];
echo "</td>";
}
else
{
echo "<td">
echo '';
echo "</td>";
}
if($arr['user_clicks'][$j]['click_type']=='email'){
echo "<td">
echo $arr['user_clicks'][$j]['click_type'];
echo "</td>";
}else
{
echo "<td">
echo '';
echo "</td>";
}
if($arr['user_clicks'][$j]['click_type']=='offline'){
echo "<td">
echo $arr['user_clicks'][$j]['click_type'];
echo "</td>";
}
else
{
echo "<td">
echo '';
echo "</td>";
}
if(!empty($arr['user_clicks'][$j]['click_count']){
echo "<td">
echo $arr['user_clicks'][$j]['click_count'];
echo "</td>";
}
else
{
echo "<td">
echo '';
echo "</td>";
}
}
echo "</tr>";
}
}

A simple php script error result with tables

Hello guys i'm in need of php experts advice.
Here's my problem. A user has 2 inputs the start and the end this are all integers. this will able to identify odd and even. i have solve already odd and even and almost done. main problem ex. start value 1 end 5. 1 is odd it should be displayed on odd in table. but the problem is it is found in even table. initial value is the problem. the rest was good.
here's my code
<?php
$firstnum = $_POST['first_input'];
$secondnum = $_POST['second_input'];
$counter = 0;
echo "<table border='1'>";
if ($firstnum < $secondnum) {
echo "<tr>"; //first tr
echo "<th>"; echo "Even numbers"; echo "</th>";
echo "<th>"; echo "Odd numbers"; echo "</th>";
echo "</tr>";
for ($counter=$firstnum; $counter <= $secondnum ; $counter++) {
if ($counter % 2 == 0){
echo "<tr>";
echo "<td>";
echo $counter;
echo "</td>";
} else {
echo "<td>";
echo $counter;
echo "</td>";
echo "</tr>";
}
}
} elseif ($firstnum > $secondnum) {
# code...
//first num is < second num
echo "<tr>"; //first tr
echo "<th>"; echo "Even numbers"; echo "</th>";
echo "<th>"; echo "Odd numbers"; echo "</th>";
echo "</tr>";
for ($counter=$firstnum; $counter >= $secondnum ; $counter--) {
if ($counter % 2 == 0){
echo "<tr>";
echo "<td>";
echo $counter;
echo "</td>";
} else {
echo "<td>";
echo $counter;
echo "</td>";
echo "</tr>";
}
}
}
echo "</table>";
?>
Your issue is you have invalid html resulting from your if/else blocks.
If your if you have
<tr>
<td><td>
and in your else you have
<td></td>
</tr>
Both of these need full row/cell tags
<tr>
<td></td>
<td></td>
</tr>
So your code should look like
if ($counter % 2 == 0){
echo "<tr>";
echo "<td>";
echo $counter;
echo "</td>";
echo "<td>";
echo "</td>";
echo "</tr>";
} else {
echo "<tr>";
echo "<td>";
echo "</td>";
echo "<td>";
echo $counter;
echo "</td>";
echo "</tr>";
}

Highlight first row in php while loop

I'm getting all rows from mysql database. Now I want to highlight only first row in php while loop with class name keywordHighlight.
How do I highlight only first row in php while loop result ?
if($numSearch > 0){
echo "<font color='green'>We found $numSearch result(s).</font>";
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<thead>";
echo "<tr>";
echo "<td class='' valign='top' width='200'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($resGetSearch = mysql_fetch_array($getSearch)){
$SearchCdid = $resGetSearch['cdid'];
$SearchFamilyName = $resGetSearch['family_name'];
$SearchGivenName = $resGetSearch['given_name'];
$SearchCompamyCid = $resGetSearch['cid'];
$SearchDepartment = $resGetSearch['department'];
$SearchTitle = $resGetSearch['title'];
$SearchComapnyName = mysql_query("SELECT company_name FROM company WHERE cid = '$SearchCompamyCid' ");
$resSearchCompanyName = mysql_fetch_array($SearchComapnyName);
$companyName = $resSearchCompanyName['company_name'];
if (strlen($companyName) >= 20) {
$companyName = substr($companyName, 0, 10). "" . substr($companyName, -5);
}else{
$companyName = $companyName;
}
// my Highlighted class = keywordHighlight";
echo "<tr onclick='getDetails($SearchCdid);' >";
echo "<td valign='top' >$companyName</td>";
echo "<td valign='top'>$SearchFamilyName</td>";
echo "<td valign='top'>$SearchGivenName</td>";
echo "<td valign='top'>$SearchDepartment</td>";
echo "<td valign='top'>$SearchTitle</td>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "<hr/>";
echo "<br/>";
}//elseif is not empty search
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
Do it like this
$i = 1;
while($resGetSearch = mysql_fetch_array($getSearch)){
$highlight = $i == 1 ? 'keywordHighlight' : '';
echo "<tr class='{$highlight}' onclick='getDetails($SearchCdid);' >";
---------------
-------------
-------------
$i++;
}
Only with CSS
or you can highlight it only with css
#highlight tbody tr:nth-child(1){
background: #ff6600;
}
There is more and elegant way to highlight only first row with only css not need to code, consider the example http://jsbin.com/soravuzakahu/1/
You could just add a boolean outside the loop. Like so:
$first = true;
while($resGetSearch = mysql_fetch_array($getSearch)){
if(first == true){
// Add code here that only applies to the first iteration.
}
$first = false;
}
<?php
if($numSearch > 0){
echo "<font color='green'>We found $numSearch result(s).</font>";
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<thead>";
echo "<tr>";
echo "<td class='' valign='top' width='200'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "<td class='' valign='top' width='125'></td>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
$i = 0;
while($resGetSearch = mysql_fetch_array($getSearch)){
++$i;
$SearchCdid = $resGetSearch['cdid'];
$SearchFamilyName = $resGetSearch['family_name'];
$SearchGivenName = $resGetSearch['given_name'];
$SearchCompamyCid = $resGetSearch['cid'];
$SearchDepartment = $resGetSearch['department'];
$SearchTitle = $resGetSearch['title'];
$SearchComapnyName = mysql_query("SELECT company_name FROM company WHERE cid = '$SearchCompamyCid' ");
$resSearchCompanyName = mysql_fetch_array($SearchComapnyName);
$companyName = $resSearchCompanyName['company_name'];
if (strlen($companyName) >= 20) {
$companyName = substr($companyName, 0, 10). "" . substr($companyName, -5);
}else{
$companyName = $companyName;
}
// my Highlighted class = keywordHighlight";
if($i == 1)
echo "<tr onclick='getDetails($SearchCdid);' >";
else
echo "<tr class='keywordHighlight' onclick='getDetails($SearchCdid);' >";
echo "<td valign='top' >$companyName</td>";
echo "<td valign='top'>$SearchFamilyName</td>";
echo "<td valign='top'>$SearchGivenName</td>";
echo "<td valign='top'>$SearchDepartment</td>";
echo "<td valign='top'>$SearchTitle</td>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "<hr/>";
echo "<br/>";
}//elseif is not empty search
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
Use a flag and set its value to true and while in loop check its value , if its true then print class name and set its value to false. Like $flag=true; then inside while loop check
if($flag==true) {
<td class='yourclassname';
$flag= false;
}
put some flag $f=0;
if f==0 then do something like this:
$highlight="<div class='keywordHighlight'>valur of first row</div>";// instead of dive you can use table also it depends on how you want to display.
$f=$f+1;
and rest in else part.
$first = true;
while ( $resGetSearch = mysql_fetch_array($getSearch) )
{
if ( $first == true )
{
// Add code here that only applies to the first iteration.
$first = false;
}
else
{
// Add code here that only applies to the 2, 3, and so on.
}
}

alignment problems in php while loop

Here i don't have any coding related problem. I'm trying to fetch the details from multiple database tables. fetch results working fine. But alignment is my problem here.
You can see a image.. In that image voucher status column is working fine. But, another two column ( room status & meal status values ) is always on the last row. How to align those (room and meal status) values properly (like voucher status column)? i hope you can understand my problem...
<?php
echo "<table width=1090 border=1 style=\"border: #ddd;\" align=center cellspacing=4 cellpadding=10>";
echo "<tr class=thvoucher>";
echo "<th width=30>Voucher Number</th>";
echo "<th width=80>Reference Number</th>";
echo "<th width=200>Guest Name</th>";
echo "<th width=150>Voucher Status</th>";
echo "<th width=150>Room Status</th>";
echo "<th width=150>Meal Status</th>";
echo "</tr>";
for($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
while($row = $stmt->fetch())
{
$voucherid = $row['VoucherID'];
$ref = $row['VoucherReference'];
$gname = $row['GuestName'];
$vstatus = $row['ActiveStatus'];
echo "<tr class=voucherstyle" . $cls . ">";
echo "<td>$voucherid</td>"; **// FIRST TD**
echo "<td>$ref</td>"; **// SECOND TD**
echo "<td>$gname</td>"; **// THIRD TD**
if( $vstatus != 'empty' ) **// FOURTH TD**
{
if( $vstatus == 'Y' )
{
echo "<td class=green >Active</td>";
}
else if( $vstatus == 'N' )
{
echo "<td class=red >Inactive</td>";
}
}
else
{
echo "<td><form method=post onsubmit=\"return mstatusvalidate(this)\"; action='voucherstatus_update.php?id_meal= $voucherid '><select name=mealstatus><option value=empty></option><option value=active>Active</option><option value=inactive>Inactive</option></select><input type=submit class=update_status title=\"Update $gname voucher status\" value=Update></form></td>";
}
}
while($r_row = $r_stmt->fetch())
{
$rstatus = $r_row['ActiveStatus'];
// same like above if else statement **// FIFTH TD**
}
while($m_row = $m_stmt->fetch())
{
$mstatus = $m_row['ActiveStatus'];
// same like above if else statement **// SIXTH TD**
}
echo "</tr>";
}
echo "</table>";
?>
You have 6 th elements in your first row, but I only see 3 td elements and no tr closing tags on subsequent rows. This is likely your issue.
I would suspect that a cursory inspection of your source output would have made this pretty clear.
try this
<?php
echo "<table width=1090 border=1 style=\"border: #ddd;\" align=center cellspacing=4 cellpadding=10>";
echo "<tr class=thvoucher>";
echo "<th width=30>Voucher Number</th>";
echo "<th width=80>Reference Number</th>";
echo "<th width=200>Guest Name</th>";
echo "<th width=150>Voucher Status</th>";
echo "<th width=150>Room Status</th>";
echo "<th width=150>Meal Status</th>";
echo "</tr>";
for($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
while($row = $stmt->fetch())
{
$voucherid = $row['VoucherID'];
$ref = $row['VoucherReference'];
$gname = $row['GuestName'];
$vstatus = $row['ActiveStatus'];
echo "<tr class=voucherstyle" . $cls . ">";
echo "<td>$voucherid</td>"; **// FIRST TD**
echo "<td>$ref</td>"; **// SECOND TD**
echo "<td>$gname</td>"; **// THIRD TD**
if( $vstatus != 'empty' ) **// FOURTH TD**
{
if( $vstatus == 'Y' )
{
echo "<td class=green >Active</td>";
}
else if( $vstatus == 'N' )
{
echo "<td class=red >Inactive</td>";
}
}
else
{
echo "<td><form method=post onsubmit=\"return mstatusvalidate(this)\"; action='voucherstatus_update.php?id_meal= $voucherid '><select name=mealstatus><option value=empty></option><option value=active>Active</option><option value=inactive>Inactive</option></select><input type=submit class=update_status title=\"Update $gname voucher status\" value=Update></form></td>";
}
while($r_row = $r_stmt->fetch())
{
$rstatus = $r_row['ActiveStatus'];
// same like above if else statement **// FIFTH TD**
}
while($m_row = $m_stmt->fetch())
{
$mstatus = $m_row['ActiveStatus'];
// same like above if else statement **// SIXTH TD**
}
echo "</tr>";
}
}
echo "</table>";
?>
I got it working using this while condition while(($row = $stmt->fetch()) && ($r_row = $r_stmt->fetch()) && ($m_row = $m_stmt->fetch())). Before i've used three separate while loops. Now, i've some other ideas. i tried it, now its working fine and alignment also perfect. Before i didn't post my if else statement code. So, everyone thought i've used just 3 td's. Sorry for confused everyone... I've posted my correct coding below..
<?php
echo "<table width=1090 border=1 style=\"border: #ddd;\" align=center cellspacing=4 cellpadding=10>";
echo "<tr class=thvoucher>";
echo "<th width=30>Voucher Number</th>";
echo "<th width=80>Reference Number</th>";
echo "<th width=200>Guest Name</th>";
echo "<th width=150>Voucher Status</th>";
echo "<th width=150>Room Status</th>";
echo "<th width=150>Meal Status</th>";
echo "</tr>";
for($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
while(($row = $stmt->fetch()) && ($r_row = $r_stmt->fetch()) && ($m_row = $m_stmt->fetch()))
{
$voucherid = $row['VoucherID'];
$ref = $row['VoucherReference'];
$gname = $row['GuestName'];
$vstatus = $row['ActiveStatus'];
echo "<tr class=voucherstyle" . $cls . ">";
echo "<td>$voucherid</td>"; **1st TD**
echo "<td>$ref</td>"; **2nd TD**
echo "<td>$gname</td>"; **3rd TD**
if( $vstatus != 'empty' ) **4th TD**
{
if( $vstatus == 'Y' )
{
echo "<td class=green >Active</td>";
}
else if( $vstatus == 'N' )
{
echo "<td class=red >Inactive</td>";
}
}
else
{
echo "<td><form method=post onsubmit=\"return mstatusvalidate(this)\"; action='voucherstatus_update.php?id= $voucherid '><select name=mealstatus><option value=empty></option><option value=active>Active</option><option value=inactive>Inactive</option></select><input type=submit class=update_status title=\"Update $gname voucher status\" value=Update></form></td>";
}
$rstatus = $r_row['ActiveStatus'];
// if else statement **5th TD**
$mstatus = $m_row['ActiveStatus'];
// if else statement **6th TD**
echo "</tr>";
}
}
echo "</table>";
?>

How to give alternating table rows different background colors using PHP

I have a table of data that is generated dynamically based on the contents stored in a mysql database.
This is how my code looks:
<table border="1">
<tr>
<th>Name</th>
<th>Description</th>
<th>URL</th>
</tr>
<?php
$query = mysql_query("SELECT * FROM categories");
while ($row = mysql_fetch_assoc($query)) {
$catName = $row['name'];
$catDes = $row['description'];
$catUrl = $row['url'];
echo "<tr class=''>";
echo "<td>$catName</td>";
echo "<td>$catDes</td>";
echo "<td>$catUrl</td>";
echo "</tr>";
}
?>
</table>
Now if the table was static, then I would just assign each alternating table row one of 2 styles in repeated order:
.whiteBackground { background-color: #fff; }
.grayBackground { background-color: #ccc; }
and that would be the end of that. However since the table rows are dynamically generated, how can I achieve this?
Or you could just use CSS:
table tr:nth-child(odd) {
background-color: #ccc;
}
<?php
$x++;
$class = ($x%2 == 0)? 'whiteBackground': 'grayBackground';
echo "<tr class='$class'>";
?>
It basically checks to see if $x is divisible evenly by 2. If it is, it is even.
P.S. if you haven't seen that style of if else query, it is called a ternary operator.
Set a variable to true/false or a number and then back again during each iteration. Or use the modulus operator such as $i%2==0 in a while loop where $i is a number and use this condition in a ternary statement or something that sets the class value of the <tr>
Easiest way to alternate row colors in PHP/HTML?
$i = 0;
while ( $row = mysql_fetch_assoc($result) ) {
echo '<tr class="' . ( ( $i %2 == 0 ) ? 'oneValue' : 'anotherValue' ) . '"><td>' . $row['something'] . '</td></tr>';
$i++;
}
<?
$color="1";
while ($line = mysql_fetch_array($result)) {
if($color==1){
echo '<tr bgcolor="">';
$color="2";
} else {
echo '<tr bgcolor="#dcdcdc">';
$color="1";
}
?><td align="left" width="40"><?= $line[name] ?></td>
<?
}
?>
This is my working code !
Here is my working part !
`
$i=1;
while($row = mysqli_fetch_array($result)) {
if($i%2==0)
{
echo '<tr bgcolor="#FFFF00">';
}
else
{
echo '<tr bgcolor="#99FFCC">';
}
$i++;
echo "<td>" . $row['blah'] . "</td>";
echo "<td>" . $row['blah_blah'] . "</td>";
echo "</tr>";
}
echo "</table>";
`
This is how I did it. I declared a css class called "even" with all the styling i wanted. Then looped through the scenario. Hope it helps!
<?php
include 'connect.php';
echo "<table id='hor-zebra'>";
$i = 0;
while($row = mysql_fetch_array($result))
{
if($i%2 == 0)
{
echo "<tr class='even'>";
echo "<td>" . $row['something'] ." ". $row['something'] . "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row['something'] ." ". $row['something'] . "</td>";
echo "</tr>";
}
$i++;
}
echo "</table>";
mysql_close($con);
?>

Categories