我想從包含兩列 - ID(int)和Name(字符串)的數據庫(MyTable)返回一個JSON對象。返回正確值類型的PHP ODBC連接
下面的腳本產生像JSON:
[{"ID":"0","Name":"John"},{"ID":"1","Name":"Doe"}]
可以看到,該ID將作爲一個字符串。我怎樣才能完成它在一個ID將返回爲整的方式:
[{"ID":0,"Name":"John"},{"ID":1,"Name":"Doe"}]
我不想讀,從ODBC解析結果數組,因爲我想用普通的查詢,如:
SELECT * FROM TableXXX
這裏是我的腳本:
//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);