0

Can anyone help with a query?

I have a php page that I want to assign a number to a variable, I want the number to be integers added together from a mySQL database. In this example, the numbers are in the "assigndatx" column, my query looks like this:

$AssignDates = mysql_query("select assigndatx from opencall where status < 2") 

(opencall is the table, I'm only wanting those with status of 0 or 1). Can anyone help me with the code to add all the results together?

5
  • 1
    Why do it in PHP when you could do it in SQL? Commented Dec 13, 2013 at 19:33
  • 1
    SUM() function maybe? Commented Dec 13, 2013 at 19:34
  • Is "adding together" the same as SUM(assigndatx)? Commented Dec 13, 2013 at 19:34
  • Why mysql_query? Legacy application? Commented Dec 13, 2013 at 20:01
  • Did you give up on this one??? Commented Jun 1, 2016 at 15:20

3 Answers 3

6
$AssignDates = mysql_query("SELECT SUM(assigndatx) as total FROM opencall WHERE status < 2") $result = mysql_fetch_assoc($AssignDates); $total = $result['total']; 

Also, I should add that you need to move away from mysql_ funcs and use mysqli_ or PDO.

Sign up to request clarification or add additional context in comments.

1 Comment

This is indeed the right way to do it, but the OP hasn't answered why he wants to do it in PHP and not MySQL. So it may not actually answer his question.
1
$sum = 0; while ($row = mysql_fetch_assoc($AssignDates) { $sum += $row['assigndatx']; } return $sum; 

Comments

0

If you switched to mysqli, you could do:

$result= mysqli_query("select assigndatx from opencall where status < 2"); $rows= mysqli_fetch_all ($result, MYSQLI_ASSOC); echo array_sum($rows); 

my personal preference would be to use

select sum(assigndatx) as total from opencall where status < 2 

for the SQL and avoid doing it at all in php.

2 Comments

I don't understand the personal preference statement. If he needs to use the data in a PHP script, he has to get any data from the MySQL result set into PHP by using mysql/mysqli/PDO extensions.
Of course I'm assuming that it's the only thing that was needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.