我试图按照从升序排列的距离来订购我的结果。我在那里创建了php函数来计算距离并返回值。当我在隔离中测试函数时,它可以工作,但是当我尝试在php select语句中调用它时,它不起作用。我哪里可能出错。以下是代码段。
<?php
include 'database.php';
$pdo = Database::connect();
function distance($lat1, $lon1, $lat2, $lon2) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
return ($miles * 1.609344);
}
$sql = 'SELECT weather_locations.location_id, weather_locations.location_name,
distance(weather_locations.latitude, weather_locations.longtitude, -20.132507, 28.626479) AS mydistance,
...
...
ORDER BY mydistance'
这些硬编码值只是为了测试。否则,我将从用户
中检索实际值答案 0 :(得分:1)
使用正确的连接
$sql = 'SELECT weather_locations.location_id, weather_locations.location_name,'.distance(weather_locations.latitude, weather_locations.longtitude, -20.132507, 28.626479).' AS mydistance ...
说明:
在你的代码中,你的函数被认为是普通字符串。所以你需要告诉php hey PHP, this is function, not a string
。因此,要将函数与其余字符串分开,请在此处进行3部分查询。
字符串第1部分(在功能之前)。
返回值(函数)。
字符串第3部分(功能之后)。
并将它们全部联系起来。
编辑2:更多解释:
第1部分:
'SELECT weather_locations.location_id, weather_locations.location_name,'
第2部分:
distance(weather_locations.latitude, weather_locations.longtitude, -20.132507, 28.626479)
第3部分:
' AS mydistance, ...'
您的代码有错误,因此您的最终查询会出现(这是您错误的代码):
'SELECT weather_locations.location_id,weather_locations.location_name,distance() AS mydistance ...'
你在哪里看到你的功能结果?它被视为字符串,因此函数不会在您的代码中执行。
所以我的最终正确查询会产生这样的结果 - &gt;
'SELECT weather_locations.location_id,weather_locations.location_name,Your result Of Function named as Distance() AS mydistance ...'
希望它有意义。
答案 1 :(得分:0)
先存储距离,然后将其插入查询。
$distance = distance($weather_locations.latitude, $weather_locations.longtitude, -20.132507, 28.626479);
$sql = 'SELECT weather_locations.location_id, weather_locations.location_name, '.
$distance.' AS mydistance, ...'
看看here如何在php中使用cancat字符串。
更新
根据你的评论我发现你误解了一些事情。 您需要先获取值,然后查询db。
$latitude_query = "SELECT latitude ..."
$longtitude_query = "SELECT longtitude ..."
$latitude = $latitude_query->fetch();
$longtitude = $longtitude_query->fetch();
$distance = distance($latitude, $longtitude, -20.132507, 28.626479);
$sql = 'SELECT weather_locations.location_id, weather_locations.location_name,
'.$distance.' AS mydistance, ...'