upperbid Posted July 1, 2009 Share Posted July 1, 2009 I am trying to return one row per user from a database that has multiple entries for many of the users. It needs to calculate the quantity and amount columns of the multiple entries for each of these specific users, but only display each user in one row. It is being called by purchase ID number. The code below doesn't work correctly. It only displays one row for the first user and not any of the others, and it calculates the quantity and amount of that displayed user from all the rows of all users. Obviously, the code is not working as it should. Any help in fixing this would be great thanks. $result = mysql_query("select * from Purchases WHERE ID = $number); $numrows=mysql_num_rows($result); $users = array(); while ($row = mysql_fetch_array($result)) { // If the user already exists in the array, // update values if (isset($users[$row["ID"]])) { $users[$row["ID"]]['quant'] += $row["Win_Qty"]; $users[$row["ID"]]['price'] += number_format($row["Bid"], 2); } // Add the user to the array else { $users[$row["ID"]] = array( 'id' => $row["ID"], 'buyer' => $row["User_ID"], 'quant' => $row["Win_Qty"], 'price' => number_format($row["Bid"], 2)); } } foreach ($users as $user) { echo "<tr><td><strong>".$user['buyer']."</strong>, ".$user['quant'].", ".$user['price']."<br /></td></tr>"; } Link to comment https://forums.phpfreaks.com/topic/164350-need-code-to-return-only-one-row-per-user-when-multiple-entries-for-some-users/ Share on other sites More sharing options...
trq Posted July 1, 2009 Share Posted July 1, 2009 You should be using sql for this. select SUM(Win_Qty) AS quant, SUM(price) AS total FROM Purchases WHERE ID = $number Link to comment https://forums.phpfreaks.com/topic/164350-need-code-to-return-only-one-row-per-user-when-multiple-entries-for-some-users/#findComment-866974 Share on other sites More sharing options...
upperbid Posted July 1, 2009 Author Share Posted July 1, 2009 I'm very limited in my MYSQL knowledge, so I'm not quite sure how I would make that query work with PHP code. Also, I think you may have used some wrong data in the query you provided. Shouldn't it read: select SUM(Win_Qty) AS quant, SUM(Bid) AS price FROM Purchases WHERE ID = $number Link to comment https://forums.phpfreaks.com/topic/164350-need-code-to-return-only-one-row-per-user-when-multiple-entries-for-some-users/#findComment-867061 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.