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;
    }
1
  • 3
    You should use placeholders in your prepared statement - you're still vulnerable to a SQL injection attack. Commented Sep 8, 2015 at 19:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.