Jump to content

Need code to return only one row per user when multiple entries for some users


upperbid

Recommended Posts

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>";
}

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.