如何在php中将数组返回给此函数?

时间:2017-04-11 10:07:30

标签: php android sql arrays json

我这里有一些PHP代码。我试图从我的数据库中获取行将它们转换为JSON数组,以便我可以在我已经制作的应用程序中使用它。我很难将数组传递给DBOperations.php到我的Function.php。

以下是DBOperations.php的代码:

//Read from diary table and enter results into an array
public function readDiaryOperation($email) 
{
    $query = $this-> conn -> prepare("SELECT title,entry FROM diary WHERE email = :email");
    $query -> execute(array(':email' => $email));

    if($query->rowCount() > 0)
    {
        $data = $query->fetchAll(PDO::FETCH_ASSOC);
        return json_encode($data);
    }
    else
    {
        $json['success'] = 0;
        $json['message'] = 'No Data found';     
        $json['myintro'] = '';

        return json_encode($json);
    }
}   

这是我的Functions.php的代码

//Login user after checking that the user exists within the database or the      fields are empty
public function readDiary($email) 
{
$db = $this -> db;

if (!empty($email)) 
{
if ($db -> readDiaryOperation($email)) 
{
   $result =  $db -> readDiaryOperation($email);

   if(!$result) 
   {
        $response["result"] = "failure";
        $response["message"] = "Read Diary Failure - Error Code 1";
        return json_encode($response);
   } 
   else 
   {
        $response["result"] = "success";
        $response["message"] = "Read Diary Operation Successful";
        $response["diary"] = $result;
        return json_encode($response);
   }
} 
else 
{
  $response["result"] = "failure";
  $response["message"] = "Read Diary Failure - Error Code 2";
  return json_encode($response);
}
} 
else 
{
     return $this -> getMsgParamNotEmpty();
}
}

$ email是使用我的应用程序改装设置的。

1 个答案:

答案 0 :(得分:0)

你将函数readDiaryOperation调用两次,这意味着,该查询总是被双重执行:

if ($db -> readDiaryOperation($email)) 
{
   $result =  $db -> readDiaryOperation($email);

顺便说一下,函数readDiaryOperation总是返回数组,所以条件:

if(!$result)
{

将始终为false且永不执行。

无论你找到多少行,都可以这样做。代码将始终返回有效结果:

$response["result"] = "success";
$response["message"] = "Read Diary Operation Successful";
$response["diary"] = $result;
return json_encode($response);

你需要那个极好的输出吗?