且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从SQL Server检索数据并将其转换为json格式?

更新时间:2022-12-12 09:06:32

我猜您的代码中有两个错误.第一个是

I guess there were two mistakes in your code. First one is

$result[] = print_r($row); 

您正在执行一个函数,并同时将值推入数组.您应该在此处将值推送到数组中.喜欢

You are executing a function and pushing values in array at same time. You should push value in array here. Like

$result[] = $row;

第二个是,在对JSON varibale进行编码后不进行打印.因此您的代码应为

And Second one is, not printing the JSON varibale after encoding it. So your code would be

$sql = "SELECT * FROM table";
$stmt = sqlsrv_query($conn, $sql);

$result = array(); 

do {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
       $result[] = $row; 
    }
} while (sqlsrv_next_result($stmt));


sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first

echo json_encode($result); //You will get the encoded array variable