Problem with Sum

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
jak82
Forum Newbie
Posts: 11
Joined: Mon Oct 15, 2007 4:21 am

Problem with Sum

Post by jak82 »

Hey there,

When I run this query

Code: Select all

$numofQuestions = count($assessmentNames);
$query = "SELECT  sum(`questionScore`) FROM `results` WHERE `sessionID`='".$_SESSION['sessionID']."'";
$result = $this->dbh->query($query);
$qscore = $result->fetch(PDO::FETCH_ASSOC);
print_r($qscore);
I get back

Code: Select all

Array ( [sum(`questionScore`)] => 300 )
How do I access the value, I tried echo $qscore[sum(`questionScore`)] ; but it does not like the sum function..

Any Ideas,

Chris
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

Code: Select all

SELECT  sum(`questionScore`) as score FROM `results`....
yields

Code: Select all

Array ( [score] => 300 )
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Moved to databases.

You could use "echo $qscore["sum(`questionScore`)"];" but that's nasty. It's better to give the column an alias. That means you assign it a name..

Code: Select all

SELECT  sum(`questionScore`) AS sum_questionScore FROM `results` WHERE `sessionID`='12345678901234567890123456789012'
Note the "as sum_questionScore" after the SUM. This means you can refer to the score sum using sum_questionScore. Obviously you could use whatever you like as a name so long as it's not one of MySQL's reserved words.

Then you can do "echo $qscore['sum_questionScore'];"
jak82
Forum Newbie
Posts: 11
Joined: Mon Oct 15, 2007 4:21 am

Thanks

Post by jak82 »

Many Thanks Guys,

Works a treat :D
Post Reply