0

I have a SQL query, I use a foreach to return these values into a JSON array. Here is how my code looks like:

$sql = "SELECT SUM(sales) from sales ... blah blah";
$result = mysqli_query($connection, $sql);
$output = array();

foreach(result as $row) {
    $output[] = $row;
}

$json = json_encode($output);
echo $json; // Returns the array

The array currently looks like this:

[{"SUM(sales)}"."10000"},[{"SUM(sales)}"."51221"},[{"SUM(sales)}"."2351"}]

I want it to be like this: [10000, 51221, 2351]

When I use decode($output) it returns NULL.

6
  • does "sales" table have a "sales" column? Commented Jan 27, 2018 at 1:36
  • (*) If your sql has user input (like from a GET or POST var), then you need to change to using a prepared statement, execute, with fetch. Otherwise you are open to sql injection attacks. Commented Jan 27, 2018 at 2:56
  • What do you mean by decode($output) ? That isn't any php function I am aware of. Commented Jan 27, 2018 at 3:00
  • @derloopkat yes Commented Jan 29, 2018 at 19:53
  • 1
    @IncredibleHat the json_decode($output), I meant. Sorry! Commented Jan 29, 2018 at 19:56

1 Answer 1

2

try this

$result = mysqli_query($connection, $sql);
$output = array();
foreach($result as $row){
    array_push($output, $row['SUM(sales)']);
}
$json = json_encode($output);
echo $json; 
Sign up to request clarification or add additional context in comments.

3 Comments

Giving some information about your solution will help a lot more to OP and to other people that visit SO, so please update your answer.
sure, i can do it tomorrow, currently I have a late evening
Also a way to make the row field selection clearer, is to adjust it in the SQL like so: SELECT SUM(sales) as SumSales FROM sales ... That way you can use $row['SumSales'] (if thats more readable for you, personally I always name SUM() and COUNT(*) and the like).

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.