douju1997 2018-02-26 16: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-26 16: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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部