0

I want to return the distance and the latitude of the closest store in my app. But when I run this script in my browser I get null. If I remove the ['latitude'], then I get array(1) { [0]=> bool(true) }. This is the way I call the function. Do I have to have a table to loop the result of the function and feed the rows?

$damn = getClosestS(37.292999, -122.555333);
        var_dump($damn); 

function getClosestDriver($plat, $plon) {
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            // set the PDO error mode to exception
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $stmt = $conn->prepare("SELECT id, latitude, longitude, ( 3959 * acos( cos( radians($plat) ) *
                    cos( radians( latitude ) ) * cos( radians( longitude ) - radians($plon) ) + 
                    sin( radians($plat) ) * sin( radians( latitude ) ) ) ) AS distance
                    FROM drivers HAVING distance < 2500 ORDER BY distance LIMIT 0 , 20");
        $stmt->execute();

            // set the resulting array to associative
        $result = array($stmt->setFetchMode(PDO::FETCH_ASSOC));
        return $result['latitude'];
        } catch (PDOException $e) {
            echo $stmt . "<br>" . $e->getMessage();
        }
        $conn = null;
    }
The_Martian
  • 3,684
  • 5
  • 33
  • 61
  • 3
    You should use placeholders in your prepared statement - you're still vulnerable to a [SQL injection attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – HPierce Sep 08 '15 at 19:55

2 Answers2

2

Setting the fetch mode won't bring back a result, it will just set the default fetch mode for the query (numeric or associative). Trying changing setFetchMode to fetchAll and remove the array(...) around it. So something like this:

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

Also, return the whole result. I'm assuming doing a query for 3 columns and then only returning the first was for debugging.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
2

According to the docs setFetchMode is designed to provide a setting and return a bool.

Could it be that you are assigning this bool to array $result and simply returning that instead of getting and returning values?

Try changing setFetchMode to fetchAll or something similar for actually gathering results from your $stmt object. And as @JonathanKuhn suggests, also remove the array(...) around it as fetchAll and its kin will return an array type by design.

sadmicrowave
  • 39,964
  • 34
  • 108
  • 180