I have a table called "items"
id month year **itemname** distmoney
1 12 2012 chicken 20
2 12 2012 pork 15
3 11 2012 chicken 21
4 11 2012 pork 15
I am trying to find the difference between the "distmoney" for the same itemname between two months FOR ONE SPECIFIC ITEM ONLY (by using WHERE id = $id)
Example:
ID 1, itemname chicken. month 12 distmoney is 20, while month 11 distmoney is 21. I want to be able to calculate the difference of 1 for id=1, itemname=chicken. It should ONLY display the difference for chicken, not any other item names (like pork).
Right now I have the php code to calculate the difference between two numbers, but I am having a tough time figuring out how to grab the previous month distmoney.
Being able to find the previous month's distmoney for a specific itemname and inserting it into a new column called "oldmoney" would also work , but I am not sure to how to do this.
Example: for id 3, itemname chicken. Current distmoney is 20, and the previous month (found in id = 1) is 20. Let's take 20 and insert it into a new column under id 3.
<?php
foreach($rows as $row):
$number1 = htmlentities($row['distmoney'])
endforeach;
$number1 = $row['distmoney'];
$number2 = ????????; // THIS NEEDS TO BE THE PREVIOUS MONTH DISTMONEY VALUE
if ($number1 <= $number2) {
$difference = "(Price Lowered) Price difference of $";
$result = $number2 - $number1;
$percent = round(100.0*($number2-$number1)/$number1);
echo $difference; echo $result; echo $percent; echo "%";
} elseif ($number1 > $number2) {
$result = $number1 - $number2;
$percent = round(100.0*($number2/$number1-1));
$addition = "(Price Higher) Price difference of $";
echo $addition; echo $result; echo $percent; echo "%";
}
?>
When you query items , ORDER BY itemname first .
Then, do something such as
//Create a variable to hold the "previous month" values
$previousItemName = '';
$previousDistMoney = '';
//Check each record from your query
foreach($rows as $row) {
//If not first time around && same item name as previous
if($previousItemName != '' && $previousItemName == $row['itemname']) {
//subtraction calculation here
//$difference = $row['distmoney'] - $previousDistMoney; ??
//echo $difference; ??
}
//Assign the "previous month" value
$previousItemName = $row['itemname'];
$previousDistMoney = $row['distmoney'];
}
Although both of these ways are slightly dirty, you could alternatively do a loop: for($i =0; $i < count($results); $i++) { }
Then check the value of $results[$i-1]['distmoney'];
Edit.
If you know the ID from your querystring, simply put that into your query... so that only the 2 'chicken' records are returned:
select itemname, distmoney from items where itemname in (
select itemname from items where id = 3
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.