Highlighting results from db - php

I reading results from DB and i would like highlight (change color) by different value:
my reading function
{
...
...
echo "<td>" . $row['value1'] . "|</td>";
echo "<td>" . $row['value2'] . "|</td>";
}
and if value1 = 1 then all results in row is red if value1 =2 then this row is green etc?
it's posible to do with php or just javascript/jquery?

It's always better to use class attribute, because at this time you may want just change background color, but later also change color, font-size or anything...
my reading function
{
...
...
echo "<td class='custom-value1-{$row['value1']}'>" . $row['value1'] . "|</td>";
echo "<td class='custom-value2-{$row['value2']}'>" . $row['value2'] . "|</td>";
}
and css:
.custom-value1-1 {
background: lightblue;
...
}
.custom-value1-2 {
background: darkblue;
...
}
this way you make your work easier and clearer.

Yes you can do it like this:
my reading function //Change this to your loop or condition
{
...
...
$style = '';
switch($row['value1']){
case 1:
$style = 'background-color:#FF0000';
break;
case 2:
$style = 'background-color:#00FF00';
break;
}
echo "<tr style='". $style ."'>";
echo "<td>" . $row['value1'] . "|</td>";
echo "<td>" . $row['value2'] . "|</td>";
...
echo "</tr>";
}

Related

How can i display my preg_match results in various divs so they can have multiple results under the correct heading?

Forgive me if this is simple but I have a for each loop that searches JSON data for results from a search. I then have some preg_match statements that will look at some of the tags within the JSON and if their is a match display the thumbnail in a div. and currently this all works. But it currently displays every result in its own Div and i want just five divs with multiple images within if there is a match.
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
if(preg_match("/_cm/i",$target)) {
echo '<div id="div5">';
echo '<h2>Creative</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SS/i",$target)) {
echo '<div id="div6">';
echo '<h2>Styled</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SH/i",$target)) {
echo '<div id="div7">';
echo '<h2>Group</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/still life/i",$target1) && preg_match("/_sm_00|_sd_00/i",$target)) {
echo '<div id="div8">';
echo '<h2>Cutout</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/worn/i",$target1)) {
echo '<div id="div9">';
echo '<h2>Worn</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
}
I cant quite figure out how to accomplish this, would it be the case of putting the results into an array and then displaying the results within the div?
Any help would be greatly appreciated.
You are right and answered the question yourself :)
Collect the results in a first step and create the markup in a second step. Something like this will do it:
$creative = [];
$styled = [];
/* ... */
function getHitInfos($theHit)
{
return [
"url" => $theHit->thumbnailUrl,
"name" => $theHit->metadata->baseName
];
}
function printResults($results, $title) {
echo '<div>';
echo '<h2>'.$title.'</h2>';
foreach ($results as $key => $val) {
echo "<img src='" . $val["url"] . "' alt='error'>";
echo $val["name"];
}
echo '</div>';
}
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
echo '<div>';
if(preg_match("/_cm/i",$target)) {
$creative[] = getHitInfos($hit)
}
if(preg_match("/_SS/i",$target)) {
$styled[] = getHitInfos($hit)
}
/* ... */
}
printResults($creative, "Creative");
printResults($styled, "Styled");
/* ... */
Disclaimer: My last contact with php is some years ago, but I hope you will see the point here.
(I also created some helping functions to DRY the code)

PHP passing values from generated textboxes

I'm creating a PHP web application in combination with SQL to order stuff. I'm randomly generating textboxes based on the amount of records I have. I want to pass the individual values to insert to the database. I want each cell to have a textbox in which I can input values and pass them with that cell. So if I want to order 2 of cell one I want to pass that value into a database.
Here's the code:
$i = 0;
if ($AanbodsTabel === false){
die(mysql_error());
}
while ($row = mysqli_fetch_array($AanbodsTabel)){
echo "<tr><td width = 4%>". htmlentities($row['Fustcode']) . "</td>";
echo "<td width = 8%>" . htmlentities($row['cultivar']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalPerFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelen']) . "</td>";
echo "<td width = 4%><input type ='text' id='Bestelbox' value='' name='AantalBestellen".$i."'></td>";
echo "<td width = 6%>" . htmlentities($row['AantalFustBesteld']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelenBesteld']) . "</td>";
135: echo '<td width = 8%><a href="Home.php?aanbodid='. htmlentities($row['aanbodid']) .'&hoeveelheid='. $_GET["AantalBestellen$i"]. '"'
. ' class = "btnBestel">Bestel</a></td></tr>';
$i = $i + 1;
}
The error I'm getting is undefined index. I guess this is because the name isn't unique. But whatever I do I still get the error.
I'm getting:
undefined index: AantalBestellen0 on line 135;
you can use javascript for example
note i will bold the code you need, the rest is context.
note this is from a similar project of mine but you should get the point.
<div id="meldingen_top_div">
<?php
echo "<div class='alert_Top_Div_Left_Outer'>
<input type='submit' value='Openstaande Meldingen' class='btnLoad' name='' onclick='toggleThis(" . '"' . "#meldTableTop" . '"' . "), toggleThis(".'"'.".alert_Top_Div_Left_Inner".'"'.")'/>
<div class='alert_Top_Div_Left_Inner'>
<table class='tableRed' id='meldTableTop'><caption/><thead/><tfoot/><tbody>";
$sqlVII = "SELECT Meldingen.Melding_id, FORMAT(Meldingen.Melding_datum, 'dd-mM-yyyy') AS Melding_datum, Producten.Product_naam, Leveranciers.Leverancier_naam, Meldingen.Melding_notitie
FROM MovieWorld.dbo.Producten,
MovieWorld.dbo.Meldingen,
MovieWorld.dbo.Categorieen,
MovieWorld.dbo.Leveranciers
WHERE Producten.Product_id = Meldingen.Product_id AND Producten.Categorie_id = Categorieen.Categorie_id AND Categorieen.Leverancier_id = Leveranciers.Leverancier_id AND Producten.Product_actief = 1 AND Meldingen.Melding_actief = 1
";
$resV= $db->executeQuery($sqlVII);
$i=1;
if($resV!=FALSE){
while($arrx = sqlsrv_fetch_array($resV)){
Code wich is relevant for you:
echo "<tr>
<td><p class='meldDate'>{$arrx['Melding_datum']}</p></td>
<td>{$arrx['Product_naam']}</td>
<td>{$arrx['Leverancier_naam']}</td>
<td><input id='txt{$i} type='text' name='thisdoesntevenmatter' value='..'/></td>
<td><img src='somerandompath.png' onclick='getTxt(".'"txt{$i}"'.")'/></td>
</tr>"
$i=$i+1;
}
}else{}echo '</tbody></table></div></div>';
?>
</div>
and the Javascript function
function getTxt(id){
var tempId = document.getElementById(id).value;
return tempId;
}
however.. you can also send the value back into a php variable, OR use AJAX to pass it to an PHP class to insert it into the Database.
edit
Your quotes in line 135: seem incorrect. try this:
echo '<td width = 8%><a href="Home.php?aanbodid={htmlentities($row['aanbodid']) }&hoeveelheid={$_GET['AantalBestellen$i']}"'
. ' class = "btnBestel">Bestel</a></td></tr>';
Where you get undefined index? on that $_POST['AantalBestellen'] ?
Use
if (isset($_POST['AantalBestellen'])) { }
to identify that the post value has been set
same do later for the hoeveelheid:
if (isset($_GET['hoeveelheid'])) { }
echo-ing the input field:
echo "<td width = 4%><input type ='text' id='Bestelbox' value='" . $_GET['hoeveelheid'] . "' name='AantalBestellen'></td>";
Also, dont forget to clear the spaces in:
'&hoeveelheid = '. $_POST //near the =

How to apply style in an echo'ed <td>?

this is my PHP code:
$query="SELECT name, surname, address FROM employee";
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td class="element">' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
And this is my CSS:
.element{
color:red;
}
But fields displayed in my HTML page aren't red. Why it doesn't work?
I already tried with
echo "<td class='element'>" . htmlspecialchars($field) . "</td>";
and
echo '<td class=\"element\">' . htmlspecialchars($field) . "</td>";
but with no success.
I suggest to specify element in your css.
td.element{
color:red;
}
Also it's a good idea to give your "tr" an ID
"tr id="myTR"...
#myTR td.element{
color:red;
}
then try this.
echo '<td style="color:red">' . htmlspecialchars($field) . '</td>';
even this 1 below shold work
echo '<td class="element">' . htmlspecialchars($field) . '</td>'; // for this just dont remove your css class
you just copy and paste to replace your code. and remove that class in css
the issue of mysl_ does not affect that not to display, i am using latest php engine and they work fine, even though we need to change.

Set color in variable

I want to set the color of the variable to red or green depending on the condition of the variable , it should appear red or green if its more and less than 0 respectively. But , the echo-ing is not allowing me to do so in the sense that the profitandloss echoed each row the has no color set.Because the rest of the row is all retrieved from database .So i would also need to echo it out. I know the method im doing is wrong. The rows are echoed on a row by row basis so the color is dependent on the value. So how do i get the colors to work by a per row basis??
if($profitandloss<$zero){
"<div style=\"color: red;\">$profitandloss</div>";
}
elseif ($profitandloss>$zero)
"<div style=\"color: green;\">$profitandloss</div>";
// }
// for profit and loss counting
//
echo "<tr><td>" . $row['trade_id'] . "</td><td>" . $row['selection'] . "</td><td>" . $row['date'] ."</td><td>" . $row['type'] ."</td><td>" . $row['size'] ."</td><td>" . $row['bidprice'] ."</td><td>" . $row['offerprice'] ."</td><td>" . $row['stoploss'] ."</td><td>" . $row['takeprofit'] ."</td><td>" . $profitandloss . "</td><td><a href ='delete.php?id=".$row['trade_id']."'>X</a></td></tr>";
You're not echoeing anything there. Your PHP script is full of errors. You can't just mix and match HTML and PHP this way.
When doing IF statements, you need to 'echo' (or store in variables) the HTML parts inside a string, and concatenate the variables to them. This way the page will display only the value of the PHP variables when rendered into HTML
if($profitandloss<$zero){
$red_div = "<div style=\"color: red;\">$profitandloss</div>"; // notice echo here
}
elseif ($profitandloss>$zero) { // you had missed this brace?
$green_div = "<div style=\"color: green;\">$profitandloss</div>";
}
then you need to output the two divs in the correct table locations.
Maybe this is what you're looking for - inserting simple condition in a row:
echo "<tr style=\"color: ".($profitandloss > $zero ? 'green' : 'red')."\"><td>" . $row['trade_id'] . "</td><td>" . (...)
or just save your result to variable and use it in the row:
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
in your row place it like that:
echo '(...) <td>Profit: '.$profitText.'</td> (...)';
you need to use echo
if($profitandloss<$zero){
echo "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero)
echo "<div style=\"color: green;\">$profitandloss</div>";
}

AJAX add data to table without resetting table.

I have a php page that will grab data from an SQL database and print it into a table, now if certain rows from the database have a certain parameter, a hidden row is inserted below that with a button to expand the row. This all works fine and I can query it with ajax into a div on a different page, but if someone were to expand the hidden row (with jquery) and the ajax update timer were to come along, it would reset and hide that row.
Here is the page that it is filled into and the ajax code to go with it:
<script type="text/javascript">
$(document).ready(function() {
$("#query").load("query.php");
var refreshId = setInterval(function() {
$("#query").load('query.php');
}, 5000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="query"></div>
And from the query.php:
while($row = mysql_fetch_array($result))
{
$decoded = json_decode($row['B'],true);
$r = $decoded['r'];
$t = $decoded['t'];
$l = $decoded['l'];
$g = $decoded['g'];
$tp = (int)$t + 3;
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td align=\"center\"><font color=\"red\">[$t]</font></td>";
echo "<td align=\"center\"><font color=\"blue\">[$r]</font></td>";
echo(((int)$t != 0) ? '<td><button class="expand stylebutton">+</button>' : '<td>');
echo $row['Name_'] . "</td>";
echo "<td>" . $row['Date_'] . "</td>";
echo "<td>" . $row['IP'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['Add'] . "</td>";
echo "<td>" . $row['Remove'] . "</td>";
echo "<td>" . $row['Comments'] . "</td>";
echo "</tr>";
if((int)$t != 0)
{
echo "<tr class=\"b\"style=\"display: none;\">";
echo "<td></td><td colspan=\"$tp\"><div style=\"color: #FC0;\"> Local:</div>";
foreach($l as $ll)
{
echo $ll . "<br>";
}
echo "<br><div style=\"color: #F00;\">Global:</div>";
foreach($g as $gg)
{
echo $gg . "<br> ";
}
echo "</td></tr>";
}
}
echo "</table>";
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function() {
$(\".stylebutton\").click(function(){
$(this).parent().parent().next().toggle();
if($(this).text() == \"+\")
{
$(this).text('-');
}
else
{
$(this).text('+');
}
});
});
</script>";
Here's an image of what one of the rows looks like when expanded.
So basically I don't want the rows to contract when the ajax update rolls through, but instead just add more data on to the page. Thanks for any help!
You should have the php file return the data in json format to be used by your jQuery. Instead of replacing the html tags and causing your UI to retract, you will replace the data.
For Example
Your php code:
$data_array = array();
while($row = mysql_fetch_array($sql)) {
array_push( $row['some_row'] , $data_array ); // add the data to an array that will later be json encoded
}
echo json_encode($data_array);
jQuery
$.ajax({
url: 'query.php',
success: function(data) {
alert('This is the JSON: ' + JSON.stringify(data));
$('#selector').text(data.some_row); // place the data inside the element with id = 'selector'
}
});

Categories