PHP PDO数组结果为空,但var_dump返回完整结果

时间:2018-10-29 13:38:33

标签: php oop pdo

我具有以下PHP函数:

public function getCad($conn,$gov)
{   
    try
    {
        //if($gov=='All')
        //{

        //}
        //else
        //{
            $sql = "SELECT * FROM governorate 
            WHERE governorate_name=:gov 
            ORDER BY governorate_name ASC";
            $exec = $conn->prepare($sql);
            $exec->bindValue(':gov', $gov);
            $exec->execute();

            $result = $exec->fetch();
            return $result;
        //}
    }
    catch(PDOExcpetion $e)
    {
        return $e->getMessage();
    }
}

结果不返回任何数据。

当我使用var_dump($result);时,将显示数据数组:

public function getCad($conn,$gov)
{   
    try
    {
        //if($gov=='All')
        //{

        //}
        //else
        //{
            $sql = "SELECT * FROM governorate 
            WHERE governorate_name=:gov 
            ORDER BY governorate_name ASC";
            $exec = $conn->prepare($sql);
            $exec->bindValue(':gov', $gov);
            $exec->execute();

            $result = $exec->fetch();var_dump($result);
            return $result;
        //}
    }
    catch(PDOExcpetion $e)
    {
        return $e->getMessage();
    }
}

在第一个脚本中,未显示任何错误,并且如果我var_dump($gov),则该值存在。

调用函数是:

<?php

require_once('../api.php');

$newApi = new api();
$conn = $newApi->connection();
$gov = 'Beirut';
$errorMsg = "Gov is not specified";
if(isset($gov))
{

    $res = $newApi->getCad($conn, $gov);
    return json_encode($res);
}
else
{
    return json_encode($errorMsg);
}

?>

1 个答案:

答案 0 :(得分:0)

在您的通话脚本中尝试

echo json_encode($res);

代替

return json_encode($res);