简体   繁体   中英

Using PHP in smarty template system to get SUM from database

Here is the code I'm currently using:

   $result = mysql_query("
SELECT SUM(s.amount) 
  FROM tblaffiliatespending s
  JOIN tblaffiliatesaccounts a
    ON a.id=s.affaccid 
  JOIN tblhosting h
    ON h.id = a.relid 
  JOIN tblproducts p
    ON p.id = h.packageid 
  JOIN tblclients c
    ON c.id = h.userid 
 WHERE affiliateid = $affiliateid 
 ORDER 
    BY clearingdate DESC;
    ");
$data = mysql_fetch_array($result);
$pendingcommissions = $data['?????????'];
$this->assign("pendingamount", $pendingcommissions);

What I'm not sure about is what to enter for ????????? on the third line. I've tried all of these things and none of them have worked:

$pendingcommissions = $data['SUM(tblaffiliatespending.amount)'];
$pendingcommissions = $data['SUM'];
$pendingcommissions = $data['tblaffiliatespending.amount'];
$pendingcommissions = $data['tblaffiliatespending'];
$pendingcommissions = $data['amount'];

Any ideas on what this needs to be changed to?

You need to give the alias for the sum of amount SUM(s.amount) total_amount so when you execute query and fetch the results from it you will have the sum of your amount column on total_amount index in resultant array and you can access it by $data['total_amount']; , also note using aggregate functions without grouping then will result in a single row not per group

SELECT SUM(s.amount) total_amount
  FROM tblaffiliatespending s
  JOIN tblaffiliatesaccounts a
    ON a.id=s.affaccid 
  JOIN tblhosting h
    ON h.id = a.relid 
  JOIN tblproducts p
    ON p.id = h.packageid 
  JOIN tblclients c
    ON c.id = h.userid 
 WHERE affiliateid = $affiliateid 
 ORDER 
    BY clearingdate DESC

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