I’m trying to create the following query in CI using ActiveRecord
SELECT *,
( 3959 * acos( cos( radians($lat) )
* cos( radians( lat ) )
* cos( radians( lng ) - radians($lng) )
+ sin( radians($lat) )
* sin( radians( lat ) ) ) ) AS distance
FROM locations
HAVING distance <= $miles
ORDER BY distance
LIMIT 0, 20
I tried
$where = "( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations";
$this->db->where($where);
$this->db->having('distance <= ' . $miles);
$this->db->order_by('distance');
$this->db->limit(20, 0);
The problem (I think) is that I’m already telling from which table I’m getting data via $query = $this->db->get('locations'); at the end of my model. So I’m getting the following error:
A Database Error Occurred Error
Number: 1064You have an error in your SQL syntax;
check the manual that corresponds to
your MySQL server version for the
right syntax to use near ‘AS distance
FROM user_profiles HAVINGdistance
<= 100 ORDER BYdistanceLIMI’ at
line 5SELECT * FROM (
locations) WHERE
country= ‘US’ ANDtags= ‘technology’ ANDdistance
( 3959 * acos( cos(
radians(25.9331488) ) * cos( radians(
lat ) ) * cos( radians( lng ) -
radians(-80.1625463) ) + sin(
radians(25.9331488) ) * sin( radians(
lat ) ) ) ) AS distance FROM
locations HAVING<= 100distance` LIMIT 20
ORDER BYFilename:
C:\wamp\www\mysite\system\database\DB_driver.phpLine Number: 330
Some things to note.. I’m using a few where() functions in my model. The distance query should coexist with other clauses.
You’re setting the
distancecalculation as aWHEREin your SQL. You want it in yourSELECT. Didn’t test, but try: