-2

I have this table in mysql database. table

This is my PHP file:

$user_latitude = 45.11123;
$user_longitude = 20.33445;

$query = "";

I want to create a query that returns the ids (of the rows in the table) in order of distance from user position($user_latitude,$user_longitude). I want to do this by using a MySQL query.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
Jhon Doe
  • 15
  • 3

1 Answers1

1

You can use the formula below to calculate the distance. For more info look here and here

$query = mysql_query("SELECT id, (6371 * acos (cos (radians($user_latitude))* cos(radians(latitude))* cos( radians($user_longitude) - radians(longitude) )+ sin (radians($user_latitude) )* sin(radians(latitude)))) AS distance FROM table_name WHERE 1 ORDER BY distance DESC");

The provided distance will be in Kilometers. If you need Miles, use 3959 instead of 6371.

Sookie Singh
  • 1,543
  • 11
  • 17