所以我上周开始学习PHP时相对较新。自从我开始写这篇文章以来,这一直给我带来了常规问题。 SQL查询使用常量变量填充,但我的应用程序试图根据用户发布到Web服务器的lat和lng值来接近用户来检索用户。因为迁移到新服务器$ _POST一直给我很多问题。我的所有脚本都可以正常工作,但这个问题始终存在问题,但现在所有$ _POST调用都返回null值。任何和所有的帮助非常感谢?下面的详细信息显示了我知道的所有信息。我的webhost是fastwebhost.com,如果有人有他们的经验,并知道他们是否有设置,我不知道我会非常有兴趣了解更多。
我正在运行php 5.5。 curl命令是:
`curl -H "Content-Type: application/json" -X POST -d '{"lat":121.1234, "lng":141.1234}' http://www.mywebsite.com/test.php
返回以下内容:
nullYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*pi()/180 )*COS(abs(lat)*pi()/180)
*POWER(SIN((-lng)*pi()/180/2),2))) '
`
我在我的PHP脚本中使用的代码是这样的:
<?php
//connection
$con = mysqli_connect("localhost","username","password");
if (!$con) {
die('Connect Error: ' . mysqli_connect_error());
}
//select db
$select_db = mysqli_select_db($con, "datbasename") or die ("cant find table");
$tableName = "users";
$origLat = $_POST['lat'];
$origLon = $_POST['lng'];
echo json_encode($origLon); //is returning null everytime
$dist = 20; // This is the maximum distance (in miles) away from $origLat, $origLon in which to search
$query = "SELECT username, profile, image_url, lat, lng, 3956 * 2 *
ASIN(SQRT( POWER(SIN(($origLat - abs(lat))*pi()/180/2),2)
+COS($origLat*pi()/180 )*COS(abs(lat)*pi()/180)
*POWER(SIN(($origLon-lng)*pi()/180/2),2)))
as distance FROM $tableName WHERE
lng between ($origLon-$dist/abs(cos(radians($origLat))*69))
and ($origLon+$dist/abs(cos(radians($origLat))*69))
and lat between ($origLat-($dist/69))
and ($origLat+($dist/69))
having distance < $dist ORDER BY distance limit 100;";
$statement = mysqli_prepare($con, $query) or die(mysqli_error($con));;
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $username, $profile, $image_url ,$lat, $lng, $distance);
$rows = array();
while(mysqli_stmt_fetch($statement)){
$row = array();
$row[username] = $username;
$row[profile] = $profile;
$row[image_url] = $image_url;
$row[distance] = $distance;
array_push($rows, $row);
}
echo json_encode($rows);
mysqli_stmt_close($statement);
mysqli_close($con)
?>
答案 0 :(得分:1)
通常情况下,POST请求将具有POST正文的键/值结构,这是您的代码$_POST['lat']
所期望的结果,其中'lat'
作为键,无论它设置为什么身体。当您将json作为正文发送时,它不会自动将json中的键/值结构转换为正常的$_POST
全局,因此您必须自己完成。
尝试这样的代码,以便从帖子体中获取json值。
$post = file_get_contents('php://input');
$json_post = json_decode($post, true);
echo $json_post['lat'] . "\n";
echo $json_post['lng'] . "\n";