Encoding json with php - php

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
**

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.

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

Related

how can I get multiple query responses in php?

Hello everyone and thanks for reading.
I'm using php to receive some queries in an android app, but I only know how to receive only one object from an array, I don't know how to receive the entire array. This is what I have done in my php document.
enter image description here
You are just getting the first result. You need to iterate over all results.
$result = mysqli_query($conn, $query);
while (($res = mysqli_fetch_assoc($result))) {
// Do jour job with $res
}
Note: Also, I've changed mysqli_fetch_array with mysqli_fetch_assoc, as you only will treat $res as an associative array.
In your case $res is array, so you need iterate over it to get acceess to rows from dtabase. For example:
$res = mysqli_fetch_array();
foreach($res as $row){
$columnValue = $row['columnName'];
}
So you need to do the same as presented in code sample as you need.

Mysql returns duplicate results with numbered key

I did a SELECT query on MySQL and get this as result.
The problem is how can I remove the 2nd duplicated results at for instance we use the 1st item in the list. "0":"1" is a duplicate for "id":"1" I would rather use "id" instead of "0" as the key later on the the app. How could I remove this to simplify the results. I do notice that the "0" means the 1st column as the successive columns does add up by 1.
Here's the $query I run.
SELECT id FROM clubsinformation WHERE :comparisonTime < updateTime
This is caused by most likely the fetching mode, you need to fetch it by associative indices only because right now you're including both associative and numeric index fetching:
No matter what DB API you got, MySQLi or PDO, just set it to associative.
So that it turn it doesn't include the numeric indices, only the column names as keys:
So this would roughly look like in code (from looking at your query placeholders, it seems PDO, so I'll draft a PDO example):
$data = array(); // container
$query = 'SELECT * FROM clubsinformation WHERE :comparisonTime < updateTime';
$select = $db->prepare($query);
$select->bindValue(':comparisonTime', $comparisonTime);
$select->execute();
while($row = $select->fetch(PDO::FETCH_ASSOC)) { // associative
$data[] = $row; // only includes column names
}
// then finally, encode
echo json_encode($data);
// OR SIMPLY
// $data = $select->fetchAll(PDO::FETCH_ASSOC); // associative
// echo json_encode($data);
That fetching is by way of PDO API. If you're using MySQLi you can still use the basic idea.

PHP JSON is dropping first record

I have a line of code to convert data from database to JSON. The only problem is that the code I have seems to be dropping the first record. Any thoughts to why.
$return_arr = Array();
$query_qrySelect = "SELECT * FROM table";
$qrySelect = mysql_query($query_qrySelect, $database) or die(mysql_error());
$row_qrySelect = mysql_fetch_assoc($qrySelect);
$totalRows_qrySelect = mysql_num_rows($qrySelect);
while ($row = mysql_fetch_array($qrySelect, MYSQL_ASSOC)) {
array_push($return_arr,$row);
}
echo json_encode($return_arr);
This line:
$row_qrySelect = mysql_fetch_assoc($qrySelect);
is where you're "losing" your data.
Because you call mysql_fetch_assoc and never use the result anywhere ($row_qrySelect is never used).
According to the manual:
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

How can I stop json_encode() encoding twice?

$file_db = new PDO('sqlite:test.db');
if($file_db){
$result = $file_db->query('SELECT id FROM sample');
$encodable = array();
while($obj = $result->fetch())
{
$encodable[] = $obj;
}
$encoded = json_encode($encodable);
echo $encoded;
}else{
die("unable to conenct to db");
}
I just want to output {"id":"1"} but it also gives me "0":"1". Does anyone know why?
Result:
[{"id":"1","0":"1"},{"id":"2","0":"2"},{"id":"3","0":"3"},{"id":"4","0":"4"},{"id":"5","0":"5"},{"id":"6","0":"6"},{"id":"7","0":"7"},{"id":"8","0":"8"},{"id":"9","0":"9"},{"id":"10","0":"10"},{"id":"11","0":"11"},{"id":"12","0":"12"},{"id":"13","0":"13"},{"id":"14","0":"14"}]
Is because of the way you are fetching the data with PDO. PDOStatement::fetch enables you to choose if you want an associative array, an indexed array and more. The default is to have both. Change it to that to have the behaviour you are expecting:
while($obj = $result->fetch(PDO::FETCH_ASSOC))
$encodable returned from database contains both an index(number) and key(column name) for all values. So it is giving once for key and once for index.
You can iterate over the result and push the desired values into an array. Then encode it.
try changing this line
while($obj = $result->fetch())
to
while($obj = $result->fetch(PDO::FETCH_ASSOC))
from php documentation for fetch() constants
Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to PDO::FETCH_BOTH.
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

php: iterate recordset - easier way?

i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets.
i'd like to know if there's an easier way to iterate a recordset by creating a php class.
here's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas?
thanks
You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}
You're probably looking for a function contains word fetch in it's name.
E.g. mysql_fetch_assoc() or $pdo->fetchAll().
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach operator.

Categories