1

So here the thing:

I am developing a backend (php) that connects with Microsoft SQL Server with android application to be the user interface.

However, I am facing a problem when it comes to encoding json with php.

It is more than fair to say that I am a beginner in php.

This is my code:

$result = sqlsrv_query( $conn, 'select * from table1');
 $row = sqlsrv_fetch_array($result);
 $array = array();
while($row =sqlsrv_fetch_array($result))
{
    $array[]=$row;
}
echo json_encode(array("data"=>array_values($array)));

So the table actually has nothing so far: just two attributes: name and age

The problem here is that the return is being as follows:

{"data":[{"0":"Miriana","name":"Miriana","1":null,"age":null},{"0":"Luke","name":"Luke","1":null,"age":null},{"0":"Sara","name":"Sara","1":null,"age":null},{"0":"Fuss","name":"Fuss","1":20,"age":20}]}

There is always a number preceding the values with a value then the real key and a value.

For example:

"0":"Miriana"
 "1":null

Thanks so much for anyone who would check this out.

**I checked those links: Decode json With PHP not working Parsing JSON with PHP Encoding JSON with PHP issues with array **

Community
  • 1
  • 1
Miriana Itani
  • 865
  • 9
  • 25
  • 1
    How about just `echo json_encode($array);` ? Or if you need the key of 'data' `echo json_encode(array("data"=>$array));` – Stuart Apr 01 '16 at 19:23

2 Answers2

2

You need to specify the fetch type:

while($row =sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))

By default you get both the numeric and the associative key.

And you should probably remove the fetch before the loop as you will not get the first row in your current results.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1

The default fetch type of sqlsrv_fetch_array is SQLSRV_FETCH_BOTH, which fetches the rows as associative and numeric array, so you get both types. If you only want an associative array, set the second argument of sqlsrv_fetch_array to SQLSRV_FETCH_ASSOC.

$result = sqlsrv_query( $conn, 'select * from table1');
$array = array();
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
    $array[]=$row;
}
echo json_encode(array("data"=>array_values($array)));

Removed the first fetch, because you will not get the first row if you do that.

Reference: http://php.net/manual/en/function.sqlsrv-fetch-array.php

Charlotte Dunois
  • 4,638
  • 2
  • 20
  • 39