[英]Generate JSON Response from PHP
Im new to PHP and. 我是PHP新手。 im making mobile app and also building web service for it.
即时通讯制作移动应用程序,并为此构建网络服务。 from mobile im sending 2 parameters as a POST and want to retrieve data as a JSON data.
从移动即时通讯发送2个参数作为POST,并希望将数据检索为JSON数据。
below is my PHP code. 下面是我的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();
when i test current response is like below. 当我测试当前响应如下时。
{"Result":1,"message":"Here Data"}
but i want to retrieve result data as well along with above response message. 但我也想检索结果数据以及上述响应消息。 like below
像下面
{
"Result": 1,
"Message": "Here Data",
"Feeds": [
{
"userid": "2",
"name": "Demo",
"address": "Demo"
},
{
"userid": "2",
"name": "Demo",
"address": "Demo"
}
]
}
You want to itterate over the result from the SQL query too. 您也希望从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();
Here the solution. 这里解决。 You should also push your query result in your
$response
array. 您还应该将查询结果推送到
$response
数组中。 Used the mysqli_fetch_assoc
function. 使用了
mysqli_fetch_assoc
函数。 header('Content-Type: application/json')
must be called before any actual output is sent, I suggest you to put in the end of your script, to avoid possible mistakes 在发送任何实际输出之前,必须先调用
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.