title: Using the Haversine formula with PostgreSQL and PDO
body: <p>On my site I'm trying to get locations nearby.</p>
  
  <p>I'm trying to use the Haversine formula for this.</p>
  
  <ul>
  <li><a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Haversine_formula</a></li>
  <li><a href="https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula">MySQL Great Circle Distance (Haversine formula)</a></li>
  <li><a href="https://stackoverflow.com/questions/6885034/calculate-zipcodes-in-range">Calculate zipcodes in range</a></li>
  </ul>
  
  <p>I'm using the following query to get all the locations within a 25km radius.</p>
  
  <pre><code>SELECT id, ( 6371 * acos( cos( radians(51.8391) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(4.6265) ) + sin( radians(51.8391) ) * sin( radians( lat ) ) ) ) AS distance
  FROM shops
  HAVING distance &lt; 25
  ORDER BY name asc
  </code></pre>
  
  <p>However I think some functions may be MySQL only, because I get the following error:</p>
  
  <blockquote>
    <p>Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42883]: Undefined function: 7 ERROR: function radians(text) does not exist LINE 1: ...id, ( 6371 * acos( cos( radians(51.8391) ) * cos( radians( l... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. in ...</p>
  </blockquote>
  
  <p>Or perhaps it has to do with tha fact I have to change the text <code>lat</code> in my query. But I don't know what it should be.</p>
  
  <p>51.8391 and 4.6265 are the long and lat of my 'starting' point.</p>
  
  <p>Any help is much appreciated since I don't have any idea what to change :-)</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>It looks like that the problem is where I try to do: <code>radians(lat)</code>.</p>
  
  <p>lat is a column in my table.</p>
  
  <p>When I try to use <code>rad()</code> as hakre suggested the error changes to: <code>function rad(numeric) does not exist</code></p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>Now we're getting somewhere.</p>
  
  <p>The datatype of the columns where indeed set as text (as suggested by mu is too short). </p>
  
  <p>I've changed it to double precision.</p>
  
  <p>However now I get another error:</p>
  
  <blockquote>
    <p>Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42703]: Undefined column: 7 ERROR: column "distance" does not exist LINE 1: ...adians( lat ) ) ) ) AS distance FROM shops HAVING distance &lt;... ^ in ...</p>
  </blockquote>
  
  <p>But I thought I made an alias in the select. Any ideas?</p>
  
  <p>Also if you guys think this should go in another question just let me know and I will close this one.</p>