我有一个具有下表的数据库
对象
-------------------------------------------------------
id | id_group | title | description | lat | lng | icon
-------------------------------------------------------
我想创建一个json作为查询的答案,该查询提供纬度和经度以及半径。
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-
Headers, Authorization, X-Requested-With");
// get database connection
include_once '../config/database.php';
$database = new Database();
$db = $database->getConnection();
// get posted data
$latitude = $_GET['lat'];
$longtitude = $_GET['lng'];
$radius = $_GET['radius'];
if(
!empty($latitude) &&
!empty($longtitude) &&
!empty($radius)
){
$qry = "SELECT *,
(
6371 * acos
(
cos(
radians( :lat )
)
* cos(
radians( lat)
) * cos(
radians( lng) - radians( :lng )
) + sin(
radians( :lat )
) * sin(
radians( lat)
)
)
) AS distance
FROM objects
HAVING distance <= :radius
ORDER BY distance ASC;";
$stmt = $db->prepare($qry);
$stmt->bindParam(":lat", $latitude);
$stmt->bindParam(":lng", $longtitude);
$stmt->bindParam(":radius", $radius);
if($stmt->execute()){
while ($result = $stmt->fetch(PDO::FETCH_OBJ)) {
echo json_encode(array("type" => "FeatureCollection",
"features" => array(
"type" => "Feature",
"geometry" => array("type" => "Point",
"coordinates" => [$latitude, $longtitude]),
"properties" => array(
"ID" => $result->id,
"icon" => $result->icon,
"tags" => "",
"title" => $result->title,
"description" => $result->description))));
}
}
else{
http_response_code(503);
echo json_encode(array("message" => "Error!"));
}
}
else{
http_response_code(400);
echo json_encode(array("message" => "Data imcomplete"));
}
?>
执行后的while循环不起作用(即使执行很好),fetchColumn()在这里也不起作用,即使我有一个类似的代码也可以在相同的输入下很好地工作。