- Need help to Change Table Colors in PHP code using SQL query values with number range
- HTML table alternate row color using PHP
- config.php
- index.php
- Easiest way to alternate row colors in PHP/HTML?
- PHP IF-statement to change color of table rows ?
- 5 Answers 5
- Create Table Rows With Alternate Colours in PHP
- Odd-Even
- Multiple of A Number ‘n’
Need help to Change Table Colors in PHP code using SQL query values with number range
This is a partial of the code I have on my script. I have tried to make the backgrounds change color depending on the values and can’t get it to read the arrays correct. Placing the conditions outside the while or inside the while returns same results when printed. If the value is 100, the color should be RED If the value is above 49, the color will be yellow If the value is 0 to 49, the color will be green Will appreciate if someone would find how the BILLED_TO_DATE_PERCENTAGE would change depending on number range when SQL read pulls data.
$counter = 1; while($row = mysqli_fetch_array($result)) < if($BILLED_TO_DATE_PERCENTAGE = 100) < $tdStyle='background-color:red;'; >else < if($BILLED_TO_DATE_PERCENTAGE >79) < $tdStyle='background-color:yellow;'; >else < $tdStyle='background-color:green;'; >> echo ""; echo "" . "" . "" . $counter . "" . "" . " "; echo "" . "" . "" . $row['NUMBER'] . "" . " "; echo "" . "" . "" . $row['PROJECT'] . "" . " "; echo "" . "" . "" . $row['BILLED_TO_DATE_PERCENTAGE'] . "" . "" . " "; echo " "; $counter++; //increment counter by 1 on every pass > echo "";
Where is $BILLED_TO_DATE_PERCENTAGE coming from? Use echo to verify its value before your if condition.
the Value $BILLED_TO_DATE_PERCENTAGE is a row in the Database that contains a value from 0 to 100 when the project is completed. First value is 100 so it prints RED, all other values are different numbers but table keeps printing RED instead of Yellow or Green. The If condition only picks up first value from the first row it reads in the SQL table.
HTML table alternate row color using PHP
In this post, you will learn how to display HTML table alternate row color using the PHP programming language. The alternate row colour helps to improve the visual representation of the web page. This appearance is mostly preferred because it helps to understand the data.
In the given example, we are using the PHP programming language to select data from MySQL and display it in a tabular form. Suppose we have the following ‘employee‘ table.
CREATE TABLE IF NOT EXISTS `employee` ( `emp_id` int(11) NOT NULL AUTO_INCREMENT, `emp_name` varchar(150) NOT NULL, `email` varchar(150) NOT NULL, `phone` varchar(100) NOT NULL, `created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `is_enabled` int(11) NOT NULL, PRIMARY KEY (`emp_id`) ) INSERT INTO `employee` (`emp_id`, `emp_name`, `email`, `phone`, `created_date`, `is_enabled`) VALUES (1, 'John', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2323234543', '2019-06-05 15:36:07', 1), (2, 'Smith', This email address is being protected from spambots. You need JavaScript enabled to view it.', '9898577442', '2019-05-14 15:36:07', 1), (3, 'Priska', This email address is being protected from spambots. You need JavaScript enabled to view it.', '9393452387', '2019-05-28 15:36:07', 1), (4, 'Gaga', This email address is being protected from spambots. You need JavaScript enabled to view it.', '8482764537', '2019-06-29 15:36:07', 1);
config.php
Now, we have written database connection code to fetch data from MySQL. Make sure to replace ‘hostname‘, ‘username‘, ‘password‘ and ‘databasename‘ with your database credentials and name.
$conn = new mysqli('hostname', 'username', 'password', 'databasename'); //Check for database connection error if($conn->connect_error)< die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error); >
index.php
Here is the main PHP file, ‘index.php‘, that we will call in the browser. At the top of this page, the ‘config.php‘ file has been added.
?php require_once 'config.php'; ?> html> head> link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> style type="text/css"> .even < background-color: #66CCFF !important; >.odd < background-color: #FFB85F !important; >/style> /head> body> table> ?php $styles = array('even','odd'); $select = "SELECT * FROM employee "; $result = $conn->query($select); $i = 1; if($result->num_rows > 0)< echo 'table >'; echo 'tr>th>Employee Name/th>'; echo 'th>Email/th>'; echo 'th>Phone/th>'; echo 'th>Created Date/th>'; echo '/tr>'; while($row = $result->fetch_object()) < ?>tr class > td>?php echo htmlentities($row->emp_name); ?>/td> td>?php echo htmlentities($row->email); ?>/td> td>?php echo htmlentities($row->phone); ?>/td> td>?php echo htmlentities($row->created_date); ?>/td> /tr> ?php $i++; > > ?> /table> /body> /html>
In the above file, we have taken two CSS classes, ‘even‘ and ‘odd‘ and defined the background colour. By implementing the logic through PHP code, we have added an alternate background colour on HTML Table rows.
Easiest way to alternate row colors in PHP/HTML?
Fundamentally — no. That’s about as easy as it gets. You might rewrite it a bit shorter/cleaner, but the idea will be the same. This is how I would write it:
$c = true; // Let's not forget to initialize our variables, shall we? foreach($posts as $post) echo '$post";
Thanks for that, works perfectly. Here’s what I changed it to to alternate between two TR classes (odd and even)
If you’d like to have less in-line PHP, a great way of doing it is via JavaScript.
Don’t forget! If you use a Javascript solution (jquery, prototype or anything else) you will have a small flick when page loads. In fact, until the page is fully loaded, you won’t have the «Zebra» on your rows. For some people this might be a problem.
I second this as well. Making odd-numbered cells a different color is a design concern, so it would be best to deal with in in JS or CSS rather than the business logic (PHP).
Using CSS3 you can do something like this:
But better not use that for a few years if you actually want your users to see the color.
i always name my zebra rows «row0» and «row1» — this makes the code a bit simpler.
@thrashr :if you foreach ($rows as $i => $row) you can remove the $i = 0 . But all this depends on getting your rows as an array before you can foreach over them.
Maybe a function with a static variable?
Then to use it (using your example):
You only define the function once, then have a nice short and very readable call to the function everywhere you want to use it.
That seems like a pretty good example but it seems like for these basics it’s nice to have a snippet that you can just throw in whenever it pops up.
statics may be difficult to read/understand at first glance. The idiom in the OP is better understood. Also, this doesn’t work if you have more than one thing alternating at once (rows then columns, for example, would break with an odd number of columns).
Would be the simplest and clearest way to do it.
You can encapsulate the logic as follows:
nickf: (grin) Well, obviously you write the ListCycler class once and store it in your library code. When you use it, it is very simple — create a ListCycler object then call it repeatedly, all the logic is hidden.
Assuming you can use CSS3 selectors you can do something like
Even with CSS2 support and mootools (javascript library) you can substitute the style with this javascript
If you don’t have anything but php a it you can simplify a bit yous code using an array
That will generate a warning on the first iteration since $c is uninitialized, and also you’re referencing ‘c’ when you should be referencing ‘$c’, which will either generate an error or warning, or ineffective behavior. Can’t remember which.
It’s short enough as it is, but I would probably wrap it into some helper function with a clear name. That way it’s more obvious what’s going on and you won’t have to repeat that logic in all templates where you need it.
If you want to do it on the display end and are comfortable with or otherwise already using javascript, libraries like jQuery will often have :odd and :even selectors, which you can then hook up to adding specific style properties or hooking into CSS more generally by adding classes.
On a side noe, to alternate between two values a and b, a nice way of doing it in a loop is this:
You can also do this without addition and subtraction:
where ^ is the XOR operation.
If you just want to alternate between 0 and 1, you can do this:
You could of course use x as an index of colors, CSS style classes and so on.
function row_color($cnt,$even,$odd) < echo ($cnt%2) ? "" : ""; >
$cnt=0; while ($row = mysql_fetch_array ($result))
You can abuse the $GLOBAL scope to store the current selected class state, see below table_row_toggle() function. Yes, I know its dirty to abuse the $GLOBAL scope, but hey, we’re here to fix problems ain’t we? 🙂
Calling the table row toggle function in HTML:
/* function to toggle row colors in tables */ function table_row_toggle() < /* check if $trclass is defined in caller */ if(array_key_exists('trclass', $GLOBALS)) < $trclass = $GLOBALS['trclass']; >/* toggle between row1 and row2 */ if(!isset($trclass) || $trclass == 'row2') < $trclass = 'row1'; >else < $trclass = 'row2'; >/* set $trclass in caller */ $GLOBALS['trclass'] = $trclass; /* write the desired class to the caller */ echo ' '; >
PHP IF-statement to change color of table rows ?
I have the following code written below. With this code I want to fetch data from MySQL database and print(echo) the result in table rows, each row with different colour. With this code data is fetched from database successfully but my condition for change color of rows is not working. Please check my code and let me know where I’m wrong.
"; if($count % 2 == 0)< echo ''.$end['page_name'].' '; >else< echo ''.$end['page_name'].' '; > echo ""; > ?>
5 Answers 5
You’re not initializing $count to 0 and you’re not incrementing $count anywhere.
"; if($i % 2 == 0)< echo ''.$end['page_name'].' '; >else< echo ''.$end['page_name'].' '; > echo ""; $i++; > ?>
Even better would be using CSS, namely the odd and even selectors: http://www.w3.org/Style/Examples/007/evenodd
You need to put a count in the while loop rather than the total number returned by the query.
Not going to write the code for you.
Before while loop set counter to zero.
In while loop check condition of counter Then increase counter value by 1
If you like, you can shorten this code, and get the HTML out of the PHP code. This will allow editors like Notepad++ or NetBeans to highlight the HTML code too. Besided, you got that line of HTML only once, so it will be easier to maintain.
However, it is smartest to use css to style the alternating rows, or at least use a class to style the individual rows.
I used inline styling in my code which is dirty as it is. But bgcolor. Really? It is not even supported anymore in HTML 4.1 strict. It is old, it is icky.
Credit goes to Jeroen. It is his code I based this example on.
Create Table Rows With Alternate Colours in PHP
If you have a lot of rows on a table, users will find it difficult to find which cell is in what row. This is because all the rows have the same colour.
If we alternate the colours, then the table will be more understandable. We can alternate colours odd-even wise or by 3 rows etc.
It can be easily done in PHP. I will tell you two ways to do it.
Suppose this is how we output rows :
for($i=0;$i < 10;$i++)< echo "What's Up ? Sky (Troll Face) "; >
Odd-Even
Now let’s add blue colour to odd rows and green colour to even rows.
for($i=0;$i < 10;$i++)< $bg_color = $i % 2 === 0 ? "green" : "blue"; echo "What's Up ? Sky (Troll Face) "; >
The table will looks something like this (forget the row contents) :
You can also add class to the row instead of setting the «style» attribute.
Multiple of A Number ‘n’
You can change colour of every 3rd element or nth element too :
$n = 3; for($i=0;$i < 10;$i++)< $bg_color = $i % $n === 0 ? "green" : "blue"; echo "What's Up ? Sky (Troll Face) "; >
In the above case, all 3rd rows will have green background color and others would have a blue color :
You can change the value of $n as you like to change the row which will have the special background color.