0

here's the PHP/PDO.

    try {





    $query = 'SELECT Date,Close FROM DY_AAPL LIMIT 5';


    $sth = $db->prepare($query);
    $sth->execute();


    while ($row = $sth->fetch(PDO::FETCH_ASSOC)){

        $result_array=array();
        $result_array[]=$row['Close'];

    /*    $num = $row['Close'];    */

        echo json_encode($result_array);



    }


    }catch (PDOException $e){

        echo 'ERROR ' . $e->getMessage();
    }

When I attempt to access the array using javascript, it's only outputting the last value in the array. Any pointers?

    <script type="text/javascript">

       var myjson = JSON.parse('<?php echo json_encode($result_array); ?>');

        document.write(myjson); 

    </script>

I thought it might have something to do with 'JSON.parse,' but I'm not sure. Thanks in advance!

3
  • 2
    There's no reason to use JSON.parse() like that. You can just drop the JSON directly into the JavaScript source as the value of the "myjson" variable. Commented Jan 28, 2013 at 21:28
  • Pointy, if I wanted to pass the JSON to an array, would the variable simply be - "var myjson = [<?php echo json_encode($result_array); ?>];" Commented Jan 28, 2013 at 21:39
  • If you wanted to put the object value inside a JavaScript array, then yes. Commented Jan 28, 2013 at 21:52

4 Answers 4

1

Try

$result_array = array();

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {

    $result_array[]=$row['Close'];

   /*    $num = $row['Close'];    */

}

echo json_encode($result_array);

…instead of initializing and outputting the array in each loop turn.

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

Comments

0

You should echo your end result, not every iteration:

   while ($row = $sth->fetch(PDO::FETCH_ASSOC)){

        $result_array=array();
        $result_array[]=$row['Close'];


    }
 echo json_encode($result_array);

Comments

0

Try this for your PHP:

    try {
        $query = 'SELECT Date,Close FROM DY_AAPL LIMIT 5';
        $sth = $db->prepare($query);
        $sth->execute();

        $result_array=array();
        while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
            $result_array[]=$row['Close'];
        }
        echo json_encode($result_array);

    }catch (PDOException $e){

        echo 'ERROR ' . $e->getMessage();
    }

Comments

0

It's because your doing the json encode within the while-loop. Place it outside the loop so the entire array get encoded.

Also, you're initializing the array within the while-loop. Which means that it will overwrite itself each time it loops.

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.