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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题