Color table row based on variable value - php

I have a table which I fetch with jQuery from a database.
I would like to color each row based on one the value that a specific column has. Example I have column "status".
I want the row yellow if in that row the status is "progress".
I want the row red if in that row the status is "cancel"
I have tried with a class but that color the entire table,
I thought about using a variable color which will change the tr but not sure how to do that.
<style>
.yellow {
background-color: darkred;
}
</style>
<tbody>
<?php
include ('connection.php');
$sql = $link->query('SELECT * FROM job');
while($data = $sql->fetch_array()) {
echo '
<tr class="yellow">
<td>'.$data['id'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['date'].'</td>
<td>'.$data['device'].'</td>
<td>'.$data['model'].'</td>
<td>'.$data['problem'].'</td>
<td>'.$data['status'].'</td>
<td>'.$data['assigned'].'</td>
</tr>
';
}
?>
</tbody>

You could use inline style. I'm guessing that you have a 3rd status option of success, which will be green.
<?php
include ('connection.php');
$sql = $link->query('SELECT * FROM job');
while($data = $sql->fetch_array()) {
$color = $data['status'] == "cancel" ? "red" : ($data['status'] == "progress" ? "yellow" : "green");
echo '
<tr style="background-color:'.$color.'">
<td>'.$data['id'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['date'].'</td>
<td>'.$data['device'].'</td>
<td>'.$data['model'].'</td>
<td>'.$data['problem'].'</td>
<td>'.$data['status'].'</td>
<td>'.$data['assigned'].'</td>
</tr>
';
}
?>

A solution would be, to write the following in your css:
.bg-yellow {
background-color: yellow;
}
and than in PHP:
echo "<table>";
if ($data["status"] === ["expected_value"]) {
echo "<tr class='bg-yellow'>";
echo "<td>" . $data["status"] . "</td>"; // and so on
echo "</tr>";
} else {
echo "<tr>";
echo "<td>" . $data["status"] . "</td>"; // and so on
echo "</tr>";
}
echo "</table>";
I hope, it helps...

If you set the background color in your Style tag or CSS file it works global but you can use inline css like this here:
<?php
require('connection.php');
$sql = $link->query('SELECT * FROM job');
while($data = $sql->fetch_array()) {
if ($data['status'] == 'cancel') {
echo('<tr style="background-color:red">');
}
else {
if ($data['status'] == 'progress') {
echo('<tr style="background-color:yellow">');
}
else {
echo('<tr style="background-color:green">');
}
}
echo('
<td>'.$data['id'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['date'].'</td>
<td>'.$data['device'].'</td>
<td>'.$data['model'].'</td>
<td>'.$data['problem'].'</td>
<td>'.$data['status'].'</td>
<td>'.$data['assigned'].'</td>
</tr>
');
}
?>
or you gave an sepcial class to the row if the status is progress.
This is an example and I hope it helped you a bit.

My solution below is largely along the lines of what was posted earlier. However, doing it this way will give you a little more control over the semantics and color contrasts, when you want to take accessibility into account. You generally wouldn't want to pair 'black' with 'darkred' as your example seems to do. This code is also a little more concise.
<!DOCTYPE html>
<html>
<style>
td
{
padding: 0.5em;
}
.color-bg-green
{
background-color: green;
}
.color-bg-red
{
background-color: red;
}
.color-bg-yellow
{
background-color: yellow;
}
.color-bg-orange
{
background-color: orange;
}
.color-fg-white
{
color: white;
}
.color-fg-black
{
color: black;
}
</style>
<body>
<table>
<?php
$rowData = [];
$rowData[] =
['id' => 1, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'success', 'assigned' => 'Person A'];
$rowData[] =
['id' => 2, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'failure', 'assigned' => 'Person B'];
$rowData[] =
['id' => 3, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'success', 'assigned' => 'Person C'];
$rowData[] =
['id' => 4, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'pending', 'assigned' => 'Person D'];
$rowData[] =
['id' => 5, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'processing', 'assigned' => 'Person E'];
$rowData[] =
['id' => 6, 'number' => 123, 'date' => '2020-01-01', 'device' => 'Smartphone', 'model' => 'Galaxy', 'problem' => 'Lorem ipsum', 'status' => 'success', 'assigned' => 'Person F'];
foreach ($rowData as $data)
{
switch ($data['status'])
{
case 'success':
{
$rowFgColor = 'white';
$rowBgColor = 'green';
}
break;
case 'failure':
{
$rowFgColor = 'black';
$rowBgColor = 'red';
}
break;
case 'pending':
{
$rowFgColor = 'black';
$rowBgColor = 'yellow';
}
break;
default:
case 'processing':
{
$rowFgColor = 'black';
$rowBgColor = 'orange';
}
break;
}
echo "<tr class=\"color-fg-$rowFgColor color-bg-$rowBgColor\">";
foreach (['id', 'number', 'date', 'device', 'model', 'problem', 'status', 'assigned'] as $column)
echo "<td>{$data[$column]}</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>

Related

Blank page after successful form submit - Codeigniter

I am using below function to add an item to cart (which right now is an array, that will be stored in session later). Every thing is working fine only problem is that when i click "Add+" button, it stores all the values in the array but gives a blank page after.
My Controller
if($action == 'Add+') {
if($this->session->userdata('cart')== ''){
$image=$this->input->post('hidden_image');
$name= $this->input->post('hidden_name');
$price= $this->input->post('hidden_price');
$cat= $this->input->post('hidden_cat');
$id= $this->input->post('hidden_id');
$product = array("name"=>$name, "price"=>$price, "id"=>$id, "image" => $image,"cat"=>$cat);
$item= array("0"=>$product);
$this->session->set_userdata('cart',$item);
}
else{
$count= count($this->session->userdata('cart'));
$name= $this->input->post('hidden_name');
$price= $this->input->post('hidden_price');
$id= $this->input->post('hidden_id');
$image=$this->input->post('hidden_image');
$cat= $this->input->post('hidden_cat');
$product = array("name"=>$name, "price"=>$price, "id"=>$id, "image" => $image,"cat"=>$cat);
$item= array($count=>$product);
$data = $this->session->userdata('cart');
$_SESSION["cart"][$count] = $product;
}
}
if($action == 'View') {
$image=$this->input->post('hidden_image');
$name= $this->input->post('hidden_name');
$price= $this->input->post('hidden_price');
$id= $this->input->post('hidden_id');
$cat= $this->input->post('hidden_cat');
$product = array("name"=>$name, "price"=>$price, "id"=>$id, "image" => $image,"cat"=>$cat);
$this->load->view('product_head');
$this->load->view('header',$product);
$this->load->view('product',$product);
}
My View
<?php $data= array ('id'=>'productform');
echo form_open_multipart('loader/product',$data);
$data = array(
'type' => 'hidden',
'name' => 'hidden_cat',
'value' => $row->category);
$val = set_value('hidden_cat');
echo form_input($data, $val);
$data = array(
'type' => 'hidden',
'name' => 'hidden_name',
'value' => $row->name
);
$val = set_value('hidden_name');
echo form_input($data, $val);
$data = array(
'type' => 'hidden',
'name' => 'hidden_image',
'value' => $row->image
);
$val = set_value('hidden_image');
echo form_input($data, $val);
$data = array(
'type' => 'hidden',
'name' => 'hidden_id',
'value' => $row->id
);
$val = set_value('hidden_id');
echo form_input($data, $val);
$data = array(
'type' => 'hidden',
'name' => 'hidden_price',
'value' => $row->price
);
$val = set_value('hidden_price');
echo form_input($data, $val);
$data = array(
'name' => 'action',
'style' => ' background-color: #4CAF50; border: none;',
'value' => 'View'
);
echo form_submit($data);
$data = array(
'name' => 'action',
'style' => ' background-color: #4CAF50; border: none;',
'id' => 'addbtn'
);
echo form_submit($data);
echo form_close();
?>
what I want is that after successful form submit it stay on same page at same place because there are many pages that have these hidden forms for every product.

Show array data in HTML table multidimensional array in php

I have an array like this:-
$str = array(
array(
'amount' => 1.87,
'user' => 'hello',
),
array(
'amount' => 0.9,
'user' => 'test',
),
array(
'amount' => 9,
'user' => 'hello',
),
array(
'amount' => 1.4,
'user' => 'test',
)
);
Now I show this data in HTML table like this for user 'test' :-
<thead>
<tr>
<th>Amount</th>
<th>User</th>
</thead>
<tbody>
<tr>
<td><?php
foreach ($str as $new_str) {
if ($new_str['user'] == "test") {
echo $new_str['amount'];
echo "<br />";
}
}
?></td><td><?php
foreach ($str as $new_str) {
if ($new_str['user'] == "test") {
echo $new_str['user'];
echo "<br />";
}
}
?></td>
</tr>
</tbody>
But now the problem is that when I use this code it shows the amount and user as a whole instead of two different rows. How can I fix this? Any help?
You just need to move your foreach loop outside of the <tr>...</tr> structure. This should work:
<?php foreach($str as $new_str){
if($new_str['user']=="test"){
echo "<tr><td>" . $new_str['amount'] . "</td><td>" . $new_str['user'] . "</td></tr>";
}
}
?>
Output (for your data)
<tr><td>0.9</td><td>test</td></tr>
<tr><td>1.4</td><td>test</td></tr>
Your tr was not repeating. output image I hope this will help.
<?php
$str = array(
array(
'amount' => 1.87,
'user' => 'hello',
),
array(
'amount' => 0.9,
'user' => 'test' ,
),
array(
'amount' => 9,
'user' => 'hello',
),
array(
'amount' => 1.4,
'user' => 'test',
)
);
?>
<table>
<thead>
<tr>
<th>Amount</th>
<th>User</th>
</tr>
</thead>
<tbody>
<?php foreach($str as $new_str) {
if($new_str['user'] == "test"){
echo '<tr>';
echo '<td>'.$new_str['amount'].'</td>';
echo '<td>'.$new_str['user'].'</td>';
echo '</tr>';
}
} ?>
</tbody>
</table>

Can't wrap my head around array_filter()

<html>
<style>
h1 {
text-align: center;
}
div {
text-align: center;
border: 1px solid;
padding: 20px;
width: 520px;
margin: 0 auto;
}
table{
text-align: center;
border: 1px solid;
padding: 20px;
width: 520px;
margin: 0 auto;
}
</style>
<div>
<h1>Students By Major</h1>
<br>
<?PHP
$students = array(
array('name' => 'Rex Solertan', 'hrs_attempted' => 23, 'gpa_points' => 28, 'major' => 'CIT'),
array('name' => 'Rivka Alexander', 'hrs_attempted' => 41, 'gpa_points' => 103, 'major' => 'EET'),
array('name' => 'Ned Ramos', 'hrs_attempted' => 28, 'gpa_points' => 52, 'major' => 'BUS'),
array('name' => 'Zoe Martinez', 'hrs_attempted' => 30, 'gpa_points' => 93, 'major' => 'WEB'),
array('name' => 'Carl McElan', 'hrs_attempted' => 54, 'gpa_points' => 100, 'major' => 'WEB'),
array('name' => 'Bob Palla', 'hrs_attempted' => 21, 'gpa_points' => 36, 'major' => 'CIT'),
array('name' => 'Tilda Downey', 'hrs_attempted' => 31, 'gpa_points' => 86, 'major' => 'CIT'),
array('name' => 'Mary Proth', 'hrs_attempted' => 33, 'gpa_points' => 105, 'major' => 'CIT'),
array('name' => 'Zelda Rowe', 'hrs_attempted' => 12, 'gpa_points' => 39, 'major' => 'BUS'),
array('name' => 'Sue Mar', 'hrs_attempted' => 20, 'gpa_points' => 50, 'major' => 'BUS'),
array('name' => 'Max Stone', 'hrs_attempted' => 42, 'gpa_points' => 80, 'major' => 'EET'));
//**** NEED TO FIGURE OUT FILTER TO DISPLAY ONLY STUDENTS WITH CERTAIN MAJOR FOR EACH SELECT ITEM BELOW ****
if (isset($_POST["business"])) {
}
if (isset($_POST["computer_information_technology"])) {
}
if (isset($_POST["electrical_engineering_technology"])) {
}
if (isset($_POST["web_site_design"])) {
}
//WORKING CODE TO DISPLAY ALL STUDENTS NAME, GPA AND MAJOR (PROGRAM WILL RUN AS EXPECTED BUT ONLY DISPLAY REQUESTED DATA FOR ENTIRE ARRAY NOT SPECIFIC MAJORS)
echo "<table border ='1' cellspacing='0' cellpadding='3'> \n";
echo "<tr><td>Name</td><td>GPA</td><td>Major</td></tr>\n";
$length = count($students);
for ($i = 0; $i < $length; $i++) {
$points = $students[$i]['gpa_points'];
$hours = $students[$i]['hrs_attempted'];
$GPAz = ($points / $hours);
$GPA = round($GPAz, 1);
$Major = $students[$i]['major'];
$Name = $students[$i]['name'];
echo "<tr><td>$Name</td><td>$GPA</td><td>$Major</td></tr>";
}
?>
</html>
This is for a project and I'm not asking to just get the answer. I have pretty much completed the project but I just need to create a filter to only display certain array elements (major) when the select item pertaining to the element is selected from my HTML form.
I have figured out how to display the requested data for the entire array and I have been researching the array_filter() function but I do not understand how to input the data into it.
I assume I can create the filter function and use the code I already created to display the array elements I want or will that have to be re-written as well?
Can anyone enlighten me?
As you're already iterating over the array I suggest a different approach for solving your problem using in_array() function and an additional variable $filter
First create an array $filter with the majors to be displayed.
$filter = array();
if (isset($_POST["business"])) {
$filter[] = "BUS";
}
if (isset($_POST["computer_information_technology"])) {
$filter[] = "CIT";
}
if (isset($_POST["electrical_engineering_technology"])) {
$filter[] = "EET";
}
if (isset($_POST["web_site_design"])) {
$filter[] = "WEB";
}
Then inside the for loop display the element only if $Major exists in the array $filter:
if( in_array( $Major, $filter ) ) {
echo "<tr><td>$Name</td><td>$GPA</td><td>$Major</td></tr>";
}
Reference:
in_array()
A general solution:
// lookup array for majors
$major_lookup = [
"business" => 'BUS',
"computer_information_technology" => 'CIT',
"electrical_engineering_technology" => 'EET',
"web_site_design" => 'WEB',
];
// your intial students array
$students = [];
$major_filter = $_POST['major_filter'] ?: '';
// if `$major_filter` key presents in
// `$major_lookup`, then filter by it's value:
if (isset($major_lookup[$major_filter])) {
$major = $major_lookup[$major_filter];
$students = array_filter(
$students,
function($v) use ($major) {
return $v['major'] == $major;
}
);
}
// output $students as usual

How to edit the code so that the results are as we expected?

My code is like this :
<?php
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
$testArray = array(
array(
'display' => '1', // strlen = 1 => it's Continent
'uraian' => 'European Continent',
),
array(
'display' => '114', // strlen = 3 => it's Country
'uraian' => 'England Country',
),
array(
'display' => '1141444', // strlen = 7 => it's City
'uraian' => 'London City',
),
array(
'display' => '1141445',
'uraian' => 'Manchester City',
),
array(
'display' => '1141452',
'uraian' => 'Liverpool City',
),
array(
'display' => '1141454',
'uraian' => 'Oxford City',
),
array(
'display' => '115',
'uraian' => 'Spain Country',
),
array(
'display' => '1151464',
'uraian' => 'Madrid City',
),
array(
'display' => '1151465',
'uraian' => 'Barcelona City',
),
array(
'display' => '2',
'uraian' => 'Asian Continent',
),
array(
'display' => '215',
'uraian' => 'Japan Country',
),
array(
'display' => '2151474',
'uraian' => 'Tokyo City',
),
array(
'display' => '2151475',
'uraian' => 'Osaka City',
)
);
echo '<table border=1>
<tr>
<th>No</th>
<th>Description</th>
</tr>';
$i = 1;
$j = 'A';
foreach($testArray as $key)
{
echo '<tr>
<td>';
if(strlen($key['display'])==3)
{
echo romanic_number($i);
++$i;
}
if(strlen($key['display'])==7)
{
echo $j;
++$j;
}
echo '</td>
<td>';
echo $key['uraian'];
echo '</td>
</tr>';
}
echo '</table>';
?>
The result is like this : http://postimg.org/image/9jmn7mlr1/
I want the result not like that, but like this:
https://postimg.org/image/579p02c1p/
I had try to edit the code, but i'm still can't do it.
Is there any people who can help me?
You have to do two things here:
Reset both $i and $j variables once your foreach completes the traversal of one continent.
Reset variable $j once the loop completes the traversal of every city of a country.
So your foreach loop should be like this:
foreach($testArray as $key){
if(strlen($key['display'])==1){
$i = 1; $j = 'A';
}
echo '<tr><td>';
if(strlen($key['display'])==3){
echo romanic_number($i);
++$i;
$j = 'A';
}
if(strlen($key['display'])==7){
echo $j;
++$j;
}
echo '</td><td>';
echo $key['uraian'];
echo '</td></tr>';
}
If your array is always sorted properly by Continent/Country/City before you build your html code, then you can just reset the $i/$j counters when you come to a Continent
if(strlen($key['display'])==1) {$i = 1;$j = 'A';}
just place at the start of your loop
...
foreach($testArray as $key)
{
if(strlen($key['display'])==1) {$i = 1;$j = 'A';}
...

Typeahead is not show options

I have some problems with my project. I use typeahead to make a search. So, i use typeahead with handlebars. But, there is a problem because it's not show options. This is my code:
model:
public function getDataForJson($q = null)
{
if($q === null)
{
$penerimas = Penerima::findAll('');
if(empty($penerimas))
{
return array('value' => 'No Data');
}
else
{
$u = array();
foreach ($penerimas as $penerima)
{
$u[] = ['value' => $penerima->nama];
}
return $u;
}
}
else
{
$query = new Query;
$query->select(['nama'])->from('tb_penerima');
$data = $query->createCommand()->queryAll();
if(empty($data))
{
return array('value' => 'No Data');
}
else
{
$return = [];
foreach ($data as $datum)
{
$out[] = ['value' => $datum['nama']];
}
return $out;
}
}
}
view:
<?php
echo '<label class="control-label">Select Repository</label>';
$template = '<div><p class="repo-language">{{no_telepon}}</p>' .
'<p class="repo-name">{{nama}}</p>';
'<p class="repo-description">{{email}}</p></div>';
echo Typeahead::widget([
'name' => 'twitter_oss',
'options' => ['placeholder' => 'Filter as you type ...'],
'dataset' => [
[
'prefetch' => Url::to(['tertuju/getpenerima']),
'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')",
'display' => 'value',
'templates' => [
'notFound' => '<div class="text-danger" style="padding:0 8px">Unable to find repositories for selected query.</div>',
'suggestion' => new JsExpression("Handlebars.compile('{$template}')")
]
]
]
]);
?>
controller:
public function actionGetpenerima($q = null)
{
return Json::encode(Tertuju::getDataForJson($q));
}

Categories