I am trying to get the output of a JSON formatted on SQL SERVER through command FOR JSON AUTO
I need to execute the query in PHP on SQL SERVER and then output it as a legit JSON.
How should I proceed?
I normally use the code below to generate the JSON, but what if I need to get a JSON ?
$key= $_GET['key'];
$date=$_GET['date'];
$brand=$_GET['brand'];
if ($key=="...")
{
$serverName = "XXX,YYYY"; // \\MSSQLSERVER";
$connectionOptions = [
"Database" => "db",
"UID" => "user",
"PWD" => 'xxxx'
];
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(formatErrors(sqlsrv_errors()));
}
$tsql = "select * from admin_all.Datafeed FOR JSON AUTO;";
// Executes the query
$stmt = sqlsrv_query($conn, $tsql);
// Error handling
if ($stmt === false) {
die(formatErrors(sqlsrv_errors()));
}
$array = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$array[]=$row;
}
echo json_encode(array("data"=>array_values($array)));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}