Mr Chris Posted May 24, 2010 Share Posted May 24, 2010 Hello, I have a table with a number of records in it like this example, each with the same order_id However this is just an example, there could be three records with the same order_id or there could be 33. What I want to do using php is say if there is more than one record for an order_id work out the difference between the previous and the next row, as indicated on my skilfully drawn diagram between the two columns impressions and clicks :-) However, i'm not at all sure how to go about this as it has to be dynamic and as I say I will never know how many rows are in the database for each order_id? Can anyone please help or is this not possible? Thank you Quote Link to comment https://forums.phpfreaks.com/topic/202764-calculating-the-difference-between-rows-in-mysql-using-php/ Share on other sites More sharing options...
Psycho Posted May 24, 2010 Share Posted May 24, 2010 You don't state if you are going to be displaying records for multiple orders at one time or only for one order. I will assume multiple. Here is a rough example to show colums for Order ID, impressions, clicks & difference $current_order_id = 0; while($row=mysql_fetch_assoc($result)) { if($current_order_id != $row['order_id']) { //New order, reset count $current_order_id = $row['order_id']; $first_clicks = true; } else { //Same order as last $first_clicks = false; } //Calculate difference (if not first) $click_difference = ($first_clicks) ? '--' : ($row['clicks']-$last_clicks); $last_clicks = $row['clicks']; echo "<tr>\n"; echo "<td>{$row['order_id']}</td>\n"; echo "<td>{$row['impresssions']}</td>\n"; echo "<td>{$row['clicks']}</td>\n"; echo "<td>{$click_difference}</td>\n"; echo "</tr>\n"; } Quote Link to comment https://forums.phpfreaks.com/topic/202764-calculating-the-difference-between-rows-in-mysql-using-php/#findComment-1062693 Share on other sites More sharing options...
Mr Chris Posted May 24, 2010 Author Share Posted May 24, 2010 Thanks Quote Link to comment https://forums.phpfreaks.com/topic/202764-calculating-the-difference-between-rows-in-mysql-using-php/#findComment-1062767 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.