简体   繁体   English

在PHP脚本中返回值

[英]Return value in php script

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. 但是,当我在浏览器中运行此脚本时,将得到null。 If I remove the ['latitude'], then I get array(1) { [0]=> bool(true) }. 如果删除['latitude'],则得到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;
    }

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. 尝试将setFetchMode更改为fetchAll并删除其周围的array(...) 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. 我假设对3列进行查询,然后仅返回第一个用于调试。

According to the docs setFetchMode is designed to provide a setting and return a bool. 根据文档, setFetchMode旨在提供设置并返回布尔值。

Could it be that you are assigning this bool to array $result and simply returning that instead of getting and returning values? 难道是您要将此布尔值分配给$result数组,而只是返回它而不是获取和返回值?

Try changing setFetchMode to fetchAll or something similar for actually gathering results from your $stmt object. 尝试将setFetchMode更改为fetchAll或类似的东西,以从$stmt对象实际收集结果。 And as @JonathanKuhn suggests, also remove the array(...) around it as fetchAll and its kin will return an array type by design. 就像@JonathanKuhn所建议的那样,还应以fetchAll删除其周围的array(...) ,其亲属将按设计返回数组类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM