I have been working with some pagination for a client and I have run into a sorting issue. I want the pagination to work by making sure that the sorting happens with my database query. I do not want to resort to storing every row in an array and then sorting that if I don’t have to.
So I can sort by a few fields but one sort choice in particular I’m having trouble with is by location. I have a separate zipcode database which I use to calculate distances via a php script in other areas of the site. However, for pagination, I would need this calculation to happen as the database is getting results. So I began to research ways of creating custom functions. I came across the two mentioned in the summary. I think that the custom FUNCTION is something I could call in line with a query and make it a field in the result set. The PROCEDURE seems to allow multiple lines/commands but doesn’t appear as if I could use it with a query. I mean, I know I could make a query within the procedure, but I don’t think I could make something a field.
Anyway, I wanted to calculate distances on the fly in a query. so, creating a function and calling it like :
SELECT t.field1, t.field2, DISTANCE(givenzip, t.field2) as dist FROM table1 t ORDER BY dist
I’m pretty sure that MySQL has built-in trig functions to allow me to port my php script (modified of course) into a custom function:
function DistanceCalc($lat1, $lon1, $lat2, $lon2, $unit = "M", $places = 5) {
$theta = $lon1 - $lon2;
//spherical law of cosines
$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;
$unit = strtoupper($unit);
//can return in kilometers or nautical miles?
if ($unit == "K") {
return round($miles * 1.609344, $places);
} else if ($unit == "N") {
return round($miles * 0.8684, $places);
} else {
return round($miles, $places);
}
}
But I don’t know if what I want to do CAN be done, and, if so, which way to go, and, if not, an alternative method?