簡體   English   中英

從PHP生成JSON響應

[英]Generate JSON Response from PHP

我是PHP新手。 即時通訊制作移動應用程序,並為此構建網絡服務。 從移動即時通訊發送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"
        }
    ]
}

您也希望從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();

這里解決。 您還應該將查詢結果推送到$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM