从PHP

时间:2016-01-17 15:20:04

标签: php json

我是PHP新手。我正在制作移动应用程序并为其构建Web服务。 从移动设备发送2个参数作为POST并希望将数据作为JSON数据检索。

下面是我的PHP代码。

header('Content-type: application/json');
include 'connection.php';
$response = array();

$location = $_POST['location'];
$country = $_POST['country'];


        $query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
        $result = mysqli_query($conn, $query);


        if (mysqli_num_rows($result) != 0)
      {

          $response["Result"] = 1;
          $response["message"] = "Here Data";

      }else{
          $response["Result"] = 0;
          $response["message"] = "No Data";

      }



echo json_encode($response);
$conn->close();

当我测试当前的响应时如下所示。

{"Result":1,"message":"Here Data"}

但我想检索结果数据以及上面的响应消息。如下所示

{
    "Result": 1,
    "Message": "Here Data",
    "Feeds": [
        {
            "userid": "2",
            "name": "Demo",
            "address": "Demo"
        },
         {
            "userid": "2",
            "name": "Demo",
            "address": "Demo"
        }
    ]
}

2 个答案:

答案 0 :(得分:1)

您也希望对SQL查询的结果进行迭代。

header('Content-type: application/json');
include 'connection.php';
$response = array();

$location = $_POST['location'];
$country = $_POST['country'];


    $query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
    $result = mysqli_query($conn, $query);


    if (mysqli_num_rows($result) != 0)
  {

      $response["Result"] = 1;
      $response["message"] = "Here Data";
      while($feed = mysqli_fetch_array($result, MYSQLI_ASSOC){
          $response['Feeds'][] = $feed;
      }

  }else{
      $response["Result"] = 0;
      $response["message"] = "No Data";

  }



echo json_encode($response);
$conn->close();

答案 1 :(得分:1)

这里的解决方案。您还应该将查询结果推送到$response数组中。使用mysqli_fetch_assoc函数。在发送任何实际输出之前必须调用header('Content-Type: application/json'),我建议你放在脚本的末尾,以避免可能的错误

include 'connection.php';
$response = array();

$location = $_POST['location'];
$country = $_POST['country'];


$query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
$result = mysqli_query($conn, $query);


if (mysqli_num_rows($result) != 0) {

    $response["feeds"] = [];

    while ($row = mysqli_fetch_assoc($result)) {
        $response["feeds"][] = $row;
    }

    $response["Result"] = 1;
    $response["message"] = "Here Data";

} else {
    $response["Result"] = 0;
    $response["message"] = "No Data";
}

$conn->close();


header('Content-type: application/json');
echo json_encode($response);