0

I have a php script that returns me a JSON string of varchar(50) elements. I would like to sum all those numbers together and store them in a variable. Is it possible? Maybe loop trough it...

This is the output of my JSON string:

`12345678910111213141516`

PHP code

<?php

include_once("./conn.php");

if(isset($_POST["toggle_btn"])){
    if(!empty($_POST["zone_field"])){

        $sql = "SELECT * FROM results";
        $res = $conn->query($sql);

        if ($res->num_rows > 0) {
            while($row = $res->fetch_assoc()) {
                echo json_decode($row['waarde']);
            }
          } else {
            echo "No rows have been found";
          }

          $conn->close();
    } else {
        echo "Field is empty";
    }
} else {
    echo 'Did not hit the btn';
}

?>

Thanks a lot

14
  • 1
    That isn't JSON. Is this really the correct data? But yes, whatever format they're really in, it should be possible to extract all the numbers and add them up. What have you tried? Where are you stuck exactly? Commented Sep 2, 2020 at 11:21
  • Maybe add the code that arrived at this? Commented Sep 2, 2020 at 11:23
  • "i used json_encode()"... That's not possible, sorry. Not unless you did 16 separate calls to json_encode() and the concatenated the results?? But doing that doesn't make a valid JSON object. And it implies that you encoded what were originally just 16 separate numbers, so it would have been easier to just add them together before you encoded them. Commented Sep 2, 2020 at 11:24
  • @ADyson i tried to do it with a $sum that starts with 0. I went true all numbers with a foreach loop and store the sum in the $sum variable. But i only obtain errors.. Commented Sep 2, 2020 at 11:24
  • 1
    I posted the code above Commented Sep 2, 2020 at 11:27

1 Answer 1

1

You can do this much more easily with a SQL query using SUM():

SELECT SUM(waarde) AS total FROM results

And this will simplify the PHP too:

$sql = "SELECT SUM(waarde) AS total FROM results";
$res = $conn->query($sql);

if ($row = $res->fetch_assoc()) { 
    echo $row["total"]; 
}

P.S. Since you're just outputting a single number, there's no need for JSON (valid or otherwise) anywhere in this task at all.

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

Comments

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.