0

I'm having some problems returning the $distance from a prepared statement. The $station_id is echoed out and all is well there but the distance is empty.

I've also replaced the question marks and ran the query directly in phpmyadmin and it returns the distance and station_id columns so the query itself appears fine.

Having some difficulty figuring out why and wondered if anyone could shed some light on what is going wrong. Please find the code below and if you have any questions, don't hesitate to ask. Oh and for background the sql formula is the haversine formula

Any help is greatly appreciated, thanks again.

 <?php
   require_once("../includes/station.php");
   require_once("../includes/maps.php");

   global $conn;

   $latitude = 54.335;
   $longitude = -1.45007;
   //$distance = 50;

   $limit_start = 0;
   $limit_end = 5;

   //$query = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) * sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance FROM `postcodelatlng` having distance <= ".$distance;
   //$query .= ' order by distance asc limit 20, 40';

   //works
   //SELECT station_details.station_id, (((acos(sin((54.335*pi()/180)) * sin((`Latitude`*pi()/180))+cos((54.335*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((-1.45007- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance FROM `postcodelatlng`inner join station_details on station_details.post_code = postcodelatlng.postcode

   // Query uses the haversine formula to calculate distance in miles as the crow flies
   $query = "SELECT station_details.station_id,
          (((acos(sin((?*pi()/180)) * sin((`Latitude`*pi()/180))+cos((?*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((? - `Longitude`)*pi()/180))))*180/pi())*60*1.1515) AS distance
   FROM `postcodelatlng`
   INNER JOIN station_details ON station_details.post_code = postcodelatlng.postcode
   INNER JOIN core ON station_details.station_id = core.entity_id
   WHERE core.live = 1
   ORDER BY distance ASC";

   $query .= ' limit ?, ?';

   //echo $query;

   if ($stmt = $conn->prepare($query)) {
           $stmt->bind_param('sssii', $lattitude, $lattitude, $longitude, $limit_start, $limit_end);
           $stmt->execute();

           $stmt->bind_result($station_id, $distance);

           while ($stmt->fetch()) {
              echo "id: $station_id dist: $distance";
           }

           $stmt->close();
   }
   $conn->close();
   ?>
jmood
  • 77
  • 2
  • 9

0 Answers0