简体   繁体   中英

php - get data (amount) from the last week

I have a table called "transactions", and in there I input the users ID, purchase type and amount everytime someone makes a purchase on my website.

I want to show these stats to each user, for the past 7 days.

Currently, I have this:

$data = array();
for($x = 0; $x <= 6; $x++){ 
$time = time()-($x*86400);
$date = date("Y/m/d", time()-($x*86400));
$queryE = $dbh->prepare("SELECT * FROM transactions WHERE user=:username AND time=:time AND(type='upgrade' OR type='addrbl' OR type='clicks' OR type='banner') ");
$queryE->bindParam(":username",$userdata['id']);
$queryE->bindParam(":time",$time);
$queryE->execute();

$row=$queryE->fetch();
$data[] = ($row['amount'] > 0 ? $row['amount'] : 0);
$dates[] = date("Y/m/d", time()-($x*86400));   


}
$days = array('Today');
for ($i=0; $i<7;$i++)
{
  $days[$i] = date('d-m', strtotime('-'.($i+0).' day'));
}

And then to print it, I have this:

echo implode(',', $data);

Although above code simply prints out 0,0,0,0,0,0,0

If I remove the $time from the query, then it only select the first row and print out that for each day.

Example: If someone purchased 3 things, but the first thing costed $60, then it will print out 60,60,60,60,60,60,60

Can someone please help me how to select the sum of the amount, from each day and print it out?

Edited after learning time is a unix timestamp in db

Currently you are trying to fetch records for a given time (not date). Since you have a unix timestamp field time on db, you need to give an interval. Also, as there might be multiple purchases on a day, you need to SUM all amounts for a given date.

...
$begin = strtotime('today midnight');
for($x = 0; $x <= 6; $x++) {
  $end = $begin + 86400;
  $queryE = $dbh->prepare("SELECT SUM(amount) AS total FROM transactions WHERE user=:username AND time > :begin AND time <= :end AND(type='upgrade' OR type='addrbl' OR type='clicks' OR type='banner') ");
  $queryE->bindParam(":username",$userdata['id']);
  $queryE->bindParam(":begin", $begin);
  $queryE->bindParam(":end", $end);
  $queryE->execute();

  $row=$queryE->fetch();
  $data[] = $row['total'];
  $dates[] = date("Y/m/d", $begin);
  $begin -= 86400;
}
...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM