I want to return a JSON object from a database (MyTable) which contains two columns – ID (int) and Name (string).
The script below produces a JSON like:
[{"ID":"0","Name":"John"},{"ID":"1","Name":"Doe"}]
You can see, that the ID is returned as a string. How can I accomplish it in a way that an ID would be returned as integer:
[{"ID":0,"Name":"John"},{"ID":1,"Name":"Doe"}]
I do not want to read and parse the result array from the ODBC since I want to use generic queries like:
SELECT * FROM TableXXX
Here is my script:
//connection
$connstr = "Driver={SQL Server Native Client 10.0};Server=" . $this->server . ";Database=" . $this->database . ";";
$conn=odbc_connect($connstr, $this->user, $this->password);
if (!$conn) {exit("Connection Failed: " . $conn);}
//execute sql
$rs=odbc_exec($conn,"SELECT ID, Name FROM MyTable");
if (!$rs) {exit("Error in SQL");}
//retreive data into array
$data = array();
$i=0;
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn);
//output as json string
echo json_encode($data);
In general, there are no common data types in ODBC. It would be dependent on the individual ODBC drivers (and possibly different from every vendor if it were supported). I have not seen anything in the ODBC specification that describes “common” data type names. Most calls into ODBC do go through the ODBC driver manager, but I am not aware of any situations in which it would perform translation/modification of SQL statements being passed through it.
It means, that ODBC driver would not return data types. If you want to return a JSON object conatining else than strings you would have to map the data individually column by column. You can retrieve data types of the field by odbc_field_type function.
However you have to know that each database vendor returns different field names (e.g. varchar, nvarchar, ….).
Then use something like (just in reverse order):
Hope it helps.