I'm trying to set up a PHP callback function for use in our application. It needs to pull data from a SQL server, and while I can get it to work initially, it's not quite doing what I want.
Code:
//Callback function for passing queries
function queryCallback($conn, $query) {
$response = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($response)){
if ($row === false) {
die(print_r(sqlsrv_errors(), true));
}
$responseData[] = $row;
}
foreach($responseData as $v) {
$output[key($v)] = current($v);
}
$responseDataJSON = JSON_encode($output, 128);
return $responseDataJSON;
}
In the above, $conn represents our server creds, as passed to sqlsrv_connect(), and $query is the string containing the query passed to SQL. Both have been verified as working.
Issue:
This code contacts the server correctly, and runs the query, but it only returns one result. This is obviously a problem with how the loops are set up, but I just can't spot it
My feeling is that the following $row = sqlsrv_fetch_array($response)
is fetching the whole row as an array, but your usage of $output[key($v)] = current($v)
is only returning the first column with the same key, and overwriting the $output index with every iteration.
foreach($responseData as $v) {
$output[key($v)] = current($v);
}
lets say you instead perform
foreach($responseData as $k => $v) {
$output[$k] = $v;
}
At which point this is redundant as $responseData[]
already is this structure.
You may actually want this if you plan to extract just the first column out of your row.
foreach($responseData as $v) {
$output[] = current($v);
}