Jump to content

Recommended Posts

Hi, I am returning mysql rows of multiple users and purchase data which sometimes have the same user more than once because they have purchased more than one item at different times.  What I would like to do is return the rows with each user only appearing once and the quantity column and the amount column of all the rows of that user being calculated into that one row that appears so I have one row per user with the total quantity and total amount. I am using the ID of the transaction in my query to get the results.  With the code below, a column appears for each purchase of all users, but I need only one row for each user.

$result = mysql_query("select * from Purchases WHERE ID = $number");
$numrows=mysql_num_rows($result);

while($r=mysql_fetch_array($result))
{
   $id = $r["ID"];
   $buyer = $r["User_ID"];
   $quant = $r["Win_Qty"];
   $price = $r["Bid"];
   $price = number_format($price, 2);
   
  //display the row
   echo "<tr><td><B>$buyer</B>, $quant, $price</BR></td></tr>";
}

Any help would be  appreciated. Thanks.

<?php

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

Hi flyhoney,

 

This doesn't quite work. Now, it takes the first user (who happens to have multiple purchases) and only prints the line with that user, while totaling the quantity and amount from all the users to that shown user.  Please advise.  Thanks.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.