Apply CSS class to dynamic table data - php

I have a MySQL database with 35 different columns labeled 1-35. The data is displayed in a dynamic table. I am looking for the PHP code that would allow me to apply a CSS class to specific cells based on what is returned inside them.
EXAMPLE: Column 1 can return either TRUE or FALSE value. If a TRUE value is returned, I want to give that cell a different background color, or highlight it.
I have the CSS class as:
.highlight {
background-color: #FC0;
}
After the CSS class has then been applied to the specific cells from columns 1-35, I would like the PHP code that can total the number of highlighted cells in the column labeled TOTAL.
Can't seem to find the PHP code to tie all this together. If someone could advise, I'd be very grateful.

<td class="<?php if ($row['item'] == TRUE)
{
echo 'highlight';
$highlights++;
}
else
{
echo 'no_highlight';
}
?>"><?php echo $row['item'];?></td>
and then...
<td id="totalHighlights"><?php echo $highlights;?></td>
EDIT: Sample code...
<?php
//We've queried the database and passed the results into $result via mysql_fetch_assoc().
while ($row = $result)
{
//Clear highlights and values arrays for each row.
$highlights = array();
$values = array();
foreach($row as $entry)
{
if ($entry == TRUE)
{
//Put a truthy value into highlights array.
array_push($highlights, 1);
}
else
{
//Put a falsey value into highlights array.
array_push($highlights, 0);
}
//Push actual field value to values array.
array_push($values, $entry);
}
echo '<tr class="row">';
//Create cell with total highlights per row using the array_sum() of highlights.
echo '<td class="row_total_highlights">'.array_sum($highlights).'</td>';
//Create each value cell and populate them with each field value from values array.
$i = 0;
foreach ($values as $value)
{
echo '<td class="entry ';
echo ($highlights[$i] == 1 ? 'trueClass' : 'falseClass');
echo '">'.$value.'</td>';
$i++;
}
echo '</tr>';
}

Related

Dynamic table not displaying array values correct

I am currently working on a Table class in php. This class creates tables dynamic by only giving values for the column names and an array from the selected data. I am stuck on displaying the values in the correct way I want to. This is how it's looking right now:current table . I thought it could be my the array. In the array all the values are the other way around like this: array . The 2nd is before the 1st id. Here is my Table Class:
public function displayTable($columns, $values = 0)
{
$this->setTable("<table class='table table-striped table-hover'>
<thead class='thead-inverse'>
<tr>");
foreach ($columns as $columnName) {
$this->setTable($this->getTable(). "<th>".$columnName."</th>" );
}
$this->setTable($this->getTable(). "</tr></thead><tbody>");
for ($x = 0; $x != sizeof($values); $x++) {
$this->setTable($this->getTable(). "<tr>");
foreach ($values as $value) {
$this->setTable($this->getTable(). "<td>".$value[$x] ."</td>");
var_dump($value);
}
$this->setTable($this->getTable(). "</tr>");
}
$this->setTable($this->getTable(). "</tbody></table>");
var_dump($this->getTable());
}
I tried applying a order by on my select query. That will get rid of my problem on the array. Displaying the items right in the td is the issue. The td is created constantly until it got no values and starts a new array just like I showed with the picture. So is there anyway to fix the problem of displaying these values under the table header td?
By looking to your array image,it seems you use fetchAll() to get records from the db.
fetchAll() provide numeric+associative array in combination. That's why your record coming like this:-
array(
'userId'=>2,
0=>2,
'userEmail'=>'some value',
1=>'same mail id'
);
Now you have only two theads # and email, but the second foreach provide you 4 <td> after each iteration, and hense table distorted.
Solution:- You have to use fetchAll(PDO::FETCH_NUM) to resolve your issue and after that change your code like below:-
public function displayTable($columns, $values = 0){
$this->setTable("<table class='table table-striped table-hover'><thead class='thead-inverse'><tr>");
foreach ($columns as $columnName) {
$this->setTable($this->getTable(). "<th>".$columnName."</th>" );
}
$this->setTable($this->getTable(). "</tr></thead><tbody>");
for ($x = 0; $x != sizeof($values); $x++) {
$this->setTable($this->getTable(). "<tr>");
foreach ($values as $key=> $value) {
$this->setTable($this->getTable(). "<td>".$value[$key] ."</td>");
}
$this->setTable($this->getTable(). "</tr>");
}
$this->setTable($this->getTable(). "</tbody></table>");
var_dump($this->getTable());
}

Get SQLite Table Data into HTML Table

I have an SQLite database and using PHP to serve up and interact the data with.
I am trying to build an HTML table with for each SQLite table columns as the HTML Table Columns and then for each row in the SQLite table render as a for each row in the HTML table.
Issue is that each sql row data is only rendered into one html table row (with current code) (should be for each row) question would be how I go about getting the sql row data into array for looping through to render html table rows.
Currently I have;
PHP get the SQL Columns into the HTML table & SQl Row data(foreach) into HTML Table Rows (foreach)
//get table count
$countTable = $dbConnect->querySingle("SELECT COUNT(*) as count FROM ".$table['name']."");
if($countTable){
//data exists, do work
//new query to get table data
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
//init arrays
$dataColumns = array();
$dataRows = array();
while($row = $query->fetchArray(SQLITE3_ASSOC))
{
//add columns to array, checking if value exists
foreach($row as $key => $value)
{
if(in_array(''.$key.'', $dataColumns)){
//column already in array, dont add again.
}else{
//column not in array, add it.
$dataColumns[]=array(
'column'=>$key
);
}
//while in this foreach do I add the row values to an array or do it again outside this loop?
//below does not work, only adds to the one array item and renders one HTML Table row with multiple SQL Table row values
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
}
}
//build HTML table
echo '<div class="table-responsive"><table class="table"><thead><tr>';
//build columns from array... works
foreach($dataColumns as $dataColumn){
echo '<th>'.$dataColumn['column'].'</th>';
}
//close table column headers 7 start HTML table body...
echo '</tr></thead><tbody>';
//Issue is here, how do I get the each row (value is either null or not null) to
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['row_item'].'</td>';
}
echo '</tr>';
//close table body & table...
echo '</tbody></table></div>';
}else{
//table has no data
echo 'no data in the selected table';
}
I rewrote this to do it all in one loop like this.
$firstRow = true;
echo '<div class="table-responsive"><table class="table">';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
if ($firstRow) {
echo '<thead><tr>';
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr></thead>';
echo '<tbody>';
$firstRow = false;
}
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table></div>';
You might find it clearer to read? It also avoids building an array of all the dataRows in memory.
Try to replace
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
with
$dataRows[]=$row;
Put this line at first line inside your while loop (or general outside the foreach loop over your columns), because adding a row is not connected analyzing your columns.
Then, in your output foreach, you should find the rows with all columns selected from your database query inside $dataRow (here symbolized with column1, column2, …):
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['column1'].'</td>';
echo '<td>'.$dataRow['column2'].'</td>';
echo '<td>'.$dataRow['column3'].'</td>';
echo '<td>'.$dataRow['column4'].'</td>';
echo '<td>'.$dataRow['column5'].'</td>';
echo '<td>'.$dataRow['column6'].'</td>';
echo '<td>'.$dataRow['column7'].'</td>';
// etc.
}
echo '</tr>';
After all your code should look like this (a bit simplified):
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
$dataColumns = array();
$dataRows = array();
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$dataRows[] = $row;
foreach ($row as $key => $value) {
//Bilding $dataColumns, see Question
}
}
echo '<div class="table-responsive"><table class="table"><thead><tr>';
foreach ($dataColumns as $dataColumn) {
echo '<th>'.$dataColumn['column'].'</th>';
}
echo '</tr></thead><tbody>';
echo '<tr>';
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $columnName => $columnValue) {
echo '<td>'.$columnValue.'</td>';
}
}
echo '</tr>';
echo '</tbody></table></div>';
Thanks to akrys
in the while loop, but outside the foreach column loop;
//$dataRows = array();
$dataRows[]=$row;
and in the building of the HTML Table;
foreach($dataRows as $dataRow){
echo '<tr>';
foreach($dataRow as $key => $value){echo '<td>'.$value.'</td>';}
echo '</tr>';
}

Create unique single <div> element for all MySQL php results with particular value

Here is my problem. I am returning results from a mysql database and using a for loop to echo the results. Though its getting a little complicated because I am using some table data to nest inside other results. This code returns "Pablo Picasso" inside a div called "Spain", fine, but if there is "El Greco" in Spain too, then I get two "Spain" divs, rather than just the one.
So: I'd like to only return a result once for each unique value in a table column, rather than for every one.
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
foreach ($results as $row)
{
echo "<div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
$tempCountry = $row['country'];
foreach ($results as $row)
{
if ($row['country']== $tempCountry) echo "<div>artists name</div>";
}
echo "</div>";echo "</div>";
}
I'm wondering if it is the construction of the nested loop, or something else, I don't know!!! Please help
I agree with #Kalpesh that you need to order the results by country.
Right now you have multiple nested loops when all you really should need is one. Try using just one loop to go through the data. On every iteration, check the $tempCountry value to see if it different compared to the current row's country. If it is, you need to close the current <div>, open a new <div> and update the $tempCountry value. Otherwise, echo the name of the artist.
EDIT: Psuedocode added below
Retrieve data from database (the query should sort the data by country)
Initialize $tempCountry to null
Loop over every row
If $tempCountry equals this row's country
Print the artist
Else
Set $tempCountry equal to this row's Country
Close the div tag
Open a new div tag
Print the artist
Note that you do not want to close the div tag on the first time through the loop. Also, you need to close the div tag after the loop finishes.
foreach ($results as $row) {
if ($tempCountry == $row['country']) {
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
else {
$tempCountry == $row['country'];
echo "</div><div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
echo "</div>";
}
Create an empty array outside of your loop. On output push the values of $row into the array inside of your loop. Then only output if value does not already exist in the array. You can use in_array for this.
The solution I found was to nest a foreach inside another, the outer loop SELECTS with a GROUP BY.
In this example I get one outer for each country, then inside that , every person (or item) within that country (or with that column value). Really useful.
NEW CODE: SOLUTION (use GROUP BY to build outer container)
// create array to build group div
$country = mysql_query("SELECT * FROM table GROUP BY `country`");
// create array for inner contents
$result = mysql_query("SELECT * FROM table ORDER BY name");
//array for group(countries in this instance)
$countrys = array();
while ($row = mysql_fetch_assoc($country)) {
$countrys[] = $row;
}
//array for inner contents
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
$tempCountry="";
foreach ($countrys as $row)
{
$tempCountry = $row['country'];
echo "<div class=\"".$row['country']."\">";
echo $row['country'];
echo "<div class=\"Box\">";
foreach ($results as $row) {
if ($tempCountry == $row['country'])
{
echo"<div>inner contents of that group</div>";
}
}
echo "</div>";
echo "</div>";
}

Looping through Array in PHP returned from MySQL Query

I have a part of an application that loops through a return of a MySQL query (as we all know) in the form of an Array. However, I need several different format settings placed on some of the items returned, for example, one column needs Japanese currency, the other has American currency and one of the returned items is a link to an image.
I would use the names of the column, however this same function that I am using to accomplish this will be used for many different tables.
This is what I have for the loop so far.
while($row = mysql_fetch_array($result)) {
for($i=0;$i<=count($row);$i++) {
if($row[i]==$row['Yen_Price']) {// I didn't expect this to work...but this is what I would like to do.
echo "Hello";
}
echo "<td>" . $row[$i] . "</td>";
}
}
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
if ($key == 'Yen_Price') {
echo "Hello";
}
echo "<td>$value</td>";
}
}
Having said that, using the same function to process all results from all possible tables will soon be rather unmanageable. You should customized this to fit the occasion like so:
while ($row = mysql_fetch_assoc($result)) {
echo "<td>Foo: $row[foo]</td>";
echo "<td>Bar: $row[bar]</td>";
}
I'd markup these results specific to each table but if you want it to be ultimately flexible, try this smelly code
// using mysql_fetch_assoc() as we don't need the numeric indices
while($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
echo '<td>';
switch ($col) {
case 'US_Price' :
printf('$%0.2f USD', $val);
break;
case 'Yen_Price' :
printf('¥%0.2f', $val);
break;
case 'image' :
printf('<img src="%s">', htmlspecialchars($val));
break;
}
echo '</td>';
}
}
Note that this is a known antipattern and you should really think about another way to approach the problem.
Use the below code. You can modify it as you want.
$select=" WRITE YOUR SELECT QUERY HERE ";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
// YOU CAN USE HERE FOR EACH LOOP AS PER YOUR REQUIREMENTS.
Thanks
Before I became a framework fanatic I used to have a bit different approach. My db library had set of methods that returned me array of record sets. This way I keep my db interaction totally separate from how I consume the record sets. Having done this, its easy to set up a grid template which can look at array and then act accordingly. Here is some pseudo code
$recordSets = $db->returnRecordSets("select some, columns from tablename");//extra param if I need array to be associative
$recordSetsCount = count($recordSets);
if($recordSetsCount == 0){ echo 'Nothing to be done!'; //exit or return or break here}
for($i=0; $i< $recordSetsCount; $i++ == 0){
$recordSet = $recordSets[$i];
/*Inspect the $recordSet array and use it*/
}

importing and mapping data from source file to HTML tables

php newbie here..I need some PHP help ideas/examples on how to import data from a delimited text file and map them into html tables. The data should populate and be mapped under its proper header. There are instances also where each record doesn't have all the values and if no data, then we can leave it null (See sample records). I would also create a table row entry for each record.
For example, the input/source file has these entries: (they are prefixed by a number to represent the header in the html table. So data from "1-MyServer" is "server4.mra.dev.pp1" and should be under table header "Server" for example. There are instances also where the record doesn't have all the values (1-7) (See below):
1-MyServer=server4.mra.dev.pp1;2-MyLogdate=Wed Aug 11 2010;3-MyDataset=dbip.pp1;4-MyStartTime=01:00:03;5-MyDuration=00:36:09;6-MySize=41.54 GB;7-MyStatus=Succeeded;
1-MyServer=server9.mra.dev.kul;2-MyLogdate=Wed Aug 11 2010;3-MyDataset=gls202.kul_lvm;5-MyDuration=06:20:33;7-MyStatus=Succeeded;
1-MyServer=server9.mra.dev.kul;2-MyLogdate=Wed Aug 11 2010;3-MyDataset=gls101.aie_lvm;4-MyStartTime=01:00:02;
Here is a copy of my html table that I would need it to map it too:
(Also, I would not have to populate record for "2-MyLogdate" into a header)
<table id="stats">
tr>
<th>Server</th>
<th>Set</th>
<th>Start</th>
<th>Duration</th>
<th>Size</th>
<th>Status</th>
</tr>
<tr>
<td>server4.mel.dev.sp1</td>
<td>dbip.sp1</td>
<td>01:00:03</td>
<td>00:36:09</td>
<td>41.54 GB</td>
<td>Succeeded</td>
</tr>
</table>
So what I really need is a system to map these appropriately.
How would I write this in php?? Thanks!
It's all about finding the patterns in your files. In your example, it's rather easy:
[number]-[column name]=[value];
The main problem I see is that you have redundant information: the number of the column, and the columns themselves, which are repeated for every row. You can parse them away, though. It depends on what you expect from your program: will the columns order always be the same? Will there always be the same columns? How should you react to unknown columns?
Here's a quick example of what you could do, using regular expressions. This example assumes that column names are all the same, and that you want to display them all, and that they'll always be in the same order. In other words, I'm doing it the easy way.
$data = array();
$lines = file("my/log/file.log");
// this will parse every line into an associative array, discarding the header number
foreach ($lines as $line)
{
// populate $matches with arrays where indices are as follows:
// 0: the whole string (0-Foo=bar;)
// 1: the column number (0)
// 2: the column name (Foo)
// 3: the value (Bar)
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
$lineData = array();
foreach ($matches as $information)
$lineData[$information[2]] = $information[3];
$data[] = $lineData;
}
$keys = array_keys($data[0]); // you can also set this yourself
// for instance, $keys = array('MyServer', 'MyDataset'); would only display those two columns
echo '<table><tr>';
foreach ($keys as $column)
echo '<th>' . $column . '</th>';
echo '</tr>';
foreach ($data as $row)
{
echo '<tr>';
foreach ($keys as $column)
echo '<td>' . (isset($row[$column]) ? $row[$column] : '') . '</td>';
echo '</tr>';
}
echo '</table>';
something like this
$logarr = file("log.txt");
foreach ($logarr as $s) {
$s = str_replace(";","&",$s);
$a = array();
parse_str($s,$a);
echo "<tr>\n";
if (isset($a['1-MyServer'])) echo $a['1-MyServer']; else echo " "
if (isset($a['2-MyLogdate'])) echo $a['2-MyLogdate']; else echo " "
// and so on
echo "</tr>\n";
}

Categories