duan19750503 2018-05-04 12:16
浏览 15
已采纳

将PHP函数添加到MySQL查询中

I have 2 questions from this query.

$query = mysql_query($con, "SELECT id, ".calcDistance($mLat, $mLng, ."lat"., ."lng".)." as distnc FROM users WHERE fName LIKE '%".$search."%' OR lName LIKE '%".$search."%' ORDER BY distnc");

Now before I go on with the questions let me explain my variables and functions.

calcDistance() is a function that returns the distance from 2 latitudes and longitude, actually latitude and longitude of the logged in user and another user. And the parameters passed are the logged in user latitude, logged in user longitude, second user latitude and second user longitude.

$mLat is a variable for the logged in user latitude

$mLng is a variable for the logged in user longitude

lat and lng are column names in the MySQL database table called users.

Now my main aim is to show searched result ordering the result by the nearest user with the search word. Which is the reason I am using the calcDistance() function in the query.

FIRST QUESTION

When I run this query, I get a Parse error: syntax error, unexpected '.'. I don't know why I am getting this error.

SECOND QUESTION

I tried passing numbers directly as the parameters so as to stop the error I get from the 1st question. But I still get another error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given.

My aim is to order a user search according to the nearest user. Using the calcDistance() returns the distance between the logged in user and another user like I said.

The lat and lng columns are columns where each user latitude and longitude are saved

  • 写回答

1条回答 默认 最新

  • dongyou2635 2018-05-05 07:07
    关注

    And after some research, I go my answer for here https://gist.github.com/statickidz/8a2f0ce3bca9badbf34970b958ef8479

    METHOD 1

    This should roughly sort the items on distance in MySQL, and should work in SQLite. If you need to sort them preciser, you could try using the Pythagorean theorem (a^2 + b^2 = c^2) to get the exact distance.

    SELECT * FROM table ORDER BY ((lat-$user_lat)*(lat-$user_lat)) + ((lng - $user_lng)*(lng - $user_lng)) ASC
    

    METHOD 2

    SELECT id, (6371 * acos (cos ( radians($user_lat) )* cos(radians( lat ) ) * cos( radians( lng ) - radians($user_lng)) + sin ( radians($user_lat) ) * sin( radians( lat ) ))) AS distance FROM table HAVING distance < 30 ORDER BY distance LIMIT 0 , 20;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分