Compare variable against previous variable in a while loop PHP

Viewed 636

I have a while loop where I want to compare the current variable ($high) to the previous one. If the value is higher I want to show a green background and if it is lower I want to show a red background.

At the moment, if the value is higher, then it shows a red background, also it only seems to compare the latest result and not all of the values in the loop.

Link to test page

$previous = 0;
while ($row =mysql_fetch_assoc($result)){
    $high = $row['High'];
    if ($high > $previous){
        ?> <span style="background:green"><?php echo $row['High']; ?></span><?PHP
    }else{
        ?> <span style="background:red"><?php echo $row['High']; ?></span><? PHP
    }
    $previous = row;
}
2 Answers

At present the code stores the previous $row, not he specific $row['High']. Please change

$previous = $row;

to

$previous = $row['High'];

mysql_* is deprecated and removed library now, so upgrade yourself to PHP7 along with mysqli_* or PDO libraries.

$previous = row; needs to be $previous = $high;

Output:-https://eval.in/1058293

Related