puiu91
12/4/2015 - 7:34 PM

Haversine formula in PHP PDO

Haversine formula in PHP PDO

<?php

$statement = Database::getInstance()->prepare(
    "SELECT
        *
     FROM 
        table
     WHERE
        SQRT(POW(:lat - latitude , 2) + POW(:lng - longitude, 2)) * 100 < :kilometres"
);

$statement->execute(array(
    ':lat' => $inputLatitude,
    ':lng' => $inputLongitude,
    ':kilometres' => 1,
));

<?php

$statement = Database::getInstance()->prepare(
    "SELECT
        *, 
        (3959 * acos(cos(radians( :lat ))
         * cos(radians(latitude))
         * cos(radians(longitude) - radians( :lng ))
         + sin(radians( :lat ))
         * sin(radians(latitude)))) AS distance
    FROM 
        table
    HAVING
        distance < :kilometres
    ORDER BY 
        distance"
);

$statement->execute(array(
    ':lat' => $inputLatitude,
    ':lng' => $inputLongitude,
    ':kilometres' => 1,
));