2014-08-28 53 views
1

我知道如何通過JSON從MySQL數據庫中獲取單行或多行的值到我的Android應用程序。但是,我怎樣才能給結果添加一個值,告訴我查詢是否正確,而不是,添加類似錯誤代碼的東西?如何添加「錯誤代碼」結果?

這是現在我的代碼: PHP

$result = mysqli_query($con,"SELECT Role, age FROM table1"); 
$json = array(); 
while($row = mysqli_fetch_array($result)){ 
    $json[] = $row; 
} 
mysqli_close($con); 
print json_encode($json); 

的Android

 try{ 
      JSONArray jArray = new JSONArray(result); 
      for(int i=0;i<jArray.length();i++){ 
       JSONObject json_data = jArray.getJSONObject(i); 
       Log.i("log_tag","age: " + json_data.getString("age") + 
           ", role: "+json_data.getString("Role")); 
      } 
     } 
     catch(JSONException e){ 
       Log.e("log_tag", "Error parsing data "+e.toString()); 
     } 

現在,例如,查詢不成功,如果沒有數據庫中的任何用戶。 在這種情況下,我想得到一個錯誤,指出錯誤,並且錯誤代碼告訴我,錯誤代碼是什麼。否則,我會得到一個「OK消息」和結果。 我該怎麼做?

我知道這個例子,我可以通過計算android應用程序中的值來做到這一點,但我需要的是更復雜的東西,如註冊表單中的錯誤。

我希望你明白我的意思:) 謝謝!

回答

1

首先定義JSON架構/結構 - 這是API和合同進行記錄的一部分。之後,大部分內容都將「適合」,併成爲基本編程的練習。

例如考慮這個合同的定義;

{ 
    status:   - string of "success" or "fail" 
    errorMessage: - optional, an error message 
    results: [..] - array of results (always empty on non-OK status), where 
        - each result is an array of the form [role, age] 
} 

然後創建JSON結果配合合同;

$result = mysqli_query($con,"SELECT Role, age FROM table1"); 

$resp = array(); 
if ($result) { 
    // Good, also add results 
    $resp["status"] = "success"; 

    $results = array(); 
    while($row = mysqli_fetch_array($result)){ 
    $results[] = $row; 
    } 
    $resp["results"] = $results; 
} else { 
    // No good! 
    $resp["status"] = "fail"; 

    $resp["errorMessage"] = "Database query failed"; 
    // Or if this is desired to be exposed (only for development!) 
    // $resp["errorMessage"] = mysqli_error($con); 

    // No results, but keep empty JSON array to make JSON access more consistent 
    $resp["results"] = array();  
} 
mysqli_close($con); 

print json_encode($resp); 

然後更新Android客戶端以接受這個新的JSON結構。它需要進行調整以包含一個額外的等級,首先檢查status(是否「成功」?)。如果可以,請使用results陣列。如果不顯示errorMessage或以其他方式通知用戶該問題。還要注意,即使沒有返回結果,查詢也可以是「成功」的。

時間異常應被拋出是,如果JSON是正確處理 - 一切應以適當的值檢查和條件進行處理。

+0

非常感謝!我想我知道了:) – honiahaka10 2014-08-28 21:41:06