1

I'm trying to create a PHP script that will echo the average value of each of my columns and array them all in a single JSON array.

I know that this is how I can get the average for a column.

select avg(`sales`) as sales  from `mytable`

But I'm not sure how to string this together

select avg(`sales`) as sales  from `mytable`
select avg(`profit`) as profit  from `mytable`
select avg(`costs`) as costs  from `mytable`

To get something like this echo'd from PHP:

[
{
    "sales": 56812
},
{
    "profit": 2312
},
{
    "costs": 324
}
]
2
  • json_encode() - never form the JSON by hand. You could use a UNION query or JOIN to get all of the data in one shot. Commented Feb 4, 2015 at 17:12
  • You shouldn't need to run three different queries. Commented Feb 4, 2015 at 17:14

1 Answer 1

0

You're close.

select
    avg(sales) as sales,
    avg(profit) as profit,
    avg(costs) as costs
from mytable;

Note that I removed the backticks around your column and table names because they are not necessary and are just visual noise and are one other thing to make mistakes about.

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

5 Comments

Then fetch it into an associative array and use json_encode. I think is what the OP was getting at.
I tried this, but getting 500 error: $dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password); $sql= ("select avg(sales) as sales, avg(profit) as profit, avg(costs) as costs from mytable;"); $result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC); header('Content-type: application/json'); echo json_encode($result);
"500 error" isn't enough to know what the problem is. There's an actual useful error message in your web server's error log.
Sorry...thought I put that in there. The error message: Call to a member function fetchAll() on a non-object in /averages.php
This is more debugging than can be done in comments. The SQL I gave you should work, but there is apparently something else wrong with your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.