2017-04-11 50 views
1

我在這裏有一些PHP代碼。我試圖從我的數據庫中獲取行,將它們變成JSON數組,以便我可以在我也創建的應用程序中使用它。我無法將數組傳遞給從DBOperations.php到我的Function.php。如何在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(); 
} 
} 

的$電子郵件是使用改造從我的應用程序設置。

回答

0

你打電話功能readDiaryOperation兩次,是什麼意思,該查詢永遠是雙重執行:

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

順便說一句,功能readDiaryOperation總是返回數組,這樣的條件:

if(!$result) 
{ 

會永遠是假的,永遠不會執行。

因此,無論您找到多少行。代碼將始終返回有效結果:

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

您需要這樣的輸出嗎?