douju1997 2018-02-27 00:28
浏览 126
已采纳

PHP json_encode和SQL服务器回调函数只返回一个结果

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

  • 写回答

1条回答 默认 最新

  • dongpu5600 2018-02-27 00:41
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误