0

I have an array populated using an sql statement in the following manner:

$index = 0;

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
    $bookname[$index] = ($row['Bookname']);
    $subjectname[$index] = ($row['SubjectName']);
    $index++;
}

When I go to echo json encode the Arrays I get a blank [] when I know it has been populated which is really weird. Am I doing anything wrong in my context

echo json_encode($Bookname,$SubjectName);
3
  • 3
    Second param of json_encode() sets options on how to encode the data. Do not use some of your data in that place or you'll ge t really weired results. See php.net/manual/en/function.json-encode.php Commented Feb 10, 2016 at 11:32
  • @maxhb even with one param lets use $bookname it still gives [] when I test echo $Bookname[2]; it works perfectly fine and prints that element! Commented Feb 10, 2016 at 11:40
  • use var_dump(json_encode($Bookname)); or var_dump(json_encode($SubjectName)); you can not print an object or array using echo Commented Feb 10, 2016 at 11:45

3 Answers 3

2

You can use json_encode as like that:

<?php
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
    $data[$index]['bookname'] = $row['Bookname'];
    $data[$index]['subjectname'] = $row['SubjectName'];
    $index++;
}
json_encode($data); // encode your array
?>
Sign up to request clarification or add additional context in comments.

8 Comments

Still getting [] I understand that two params shouldn't be used but even with one param nothing happens
@EoinÓCribín: please use print_r($row); inside the loop and share the result.
Nothing printed at all. but if I test using my original code and say for example: echo $bookname[0] after the loop I get a resut
@EoinÓCribín: u can not use $booksname[0] with my example... well, please use print_r($data); after loop (outside the loop)
just a blank array (Array ( )) prints I was sure data was going into it.
|
2

Try following:

       $index = 0;
       $data = array();
       while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
      {
        $data['Bookname'][$index] = $row['Bookname'] 
        $data['SubjectName'][$index] = $row['SubjectName'];
        $index++;

       }
       echo json_encode($data);

Comments

1

You have passed two parameter while calling json_encode function. You batter combine two array in one. Then call the json_encode function like json_encode($combinedArray)

3 Comments

second param of json_encode is for behaviour php.net/manual/en/function.json-encode.php
It takes only one parameter ??? I doubt on this line of your answer... see @devpro 's comment.
and third param is depth :) brother

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.