我正在尝试开发一个简单的web服务,为我的Wikitude增强现实应用程序提供数据。数据将作为JSON从中提供,并从MYSQL数据库中检索。到目前为止,我能够连接到我的数据库并以JSON格式获取数据。
但是,我需要进一步开发它来发出HTTPGetMethod请求。这是我的PHP脚本
<?PHP
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","tutorial") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$getData = "select * from places";
$qur = $connection->query($getData);
while($r = mysqli_fetch_assoc($qur)){
$msg[] = array("id" => $r['id'], "longitude" => $r['longitude'], "latitude" => $r['latitude'], "description" => $r['description'], "name" => $r['name']);
}
$json = $msg;
header('content-type: application/json');
echo json_encode($json);
@mysqli_close($conn);
?>
目前,如果我以
的身份提出请求http://localhost/json_internet2.php?longitude=13.88345
,结果是来自数据库的所有数据。因此,它不起作用。
我该怎么做呢?任何帮助都是有益的。
感谢
假设您的数据库有一个"经度"列,您需要修改SQL查询以考虑GET变量(在您的示例中为经度),并使用它来过滤结果。
示例:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","tutorial") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$getData = "select * from places";
if(isset($_GET['longitude']) && !empty($_GET['longitude'])){
$longitude = mysqli_real_escape_string($_GET['longitude']);
$getData = "select * from places WHERE longitude = '$longitude' ";
}
$qur = $connection->query($getData);
while($r = mysqli_fetch_assoc($qur)){
$msg[] = array("id" => $r['id'], "longitude" => $r['longitude'], "latitude" => $r['latitude'], "description" => $r['description'], "name" => $r['name']);
}
$json = $msg;
header('content-type: application/json');
echo json_encode($json);
@mysqli_close($conn);
这超出了这个问题的范围,但请注意,对于安全问题,您应该真正使用PDO和准备好的语句。更多信息:http://php.net/manual/en/pdo.prepared-statements.php