2012-04-05 71 views
4

我想從我的MySQL數據庫檢索特定的數據,通過傳遞來自Android的參數的值,然後在查詢中的PHP腳本中讀取此值以便返回數據。從android和MYSQL數據庫連接返回的空值

當我運行應用程序時發生錯誤解析數據異常,因爲返回的結果值爲空?

爲什麼結果爲空?是來自PHP腳本還是來自我的java代碼的錯誤?

請幫我

在此先感謝!

city.php:

<?php 
    mysql_connect("localhost","username","password"); 
    mysql_select_db("Countries"); 
    $sql=mysql_query("select City_Population from City where Name= "'.$_REQUEST['Name']."'"); 
    while($row=mysql_fetch_assoc($sql)) 
    $output[]=$row; 
     print(json_encode($output)); 
     mysql_close(); 
     ?> 

塊引用

java類:

 public class ConnectActivity extends ListActivity { 

      String add="http://10.0.2.2/city.php"; 
      public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 

      new Connect().execute(); 

     } 

    private class Connect extends AsyncTask<Void,Void,String> 
    {  
      private String result = ""; 
      private InputStream is=null; 
      private String city_name="London"; 
      protected String doInBackground(Void... params) { 
      try 
      { 
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       nameValuePairs.add(new BasicNameValuePair("Name",city_name)); 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost(add); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 
       } 
     catch(Exception e) 
      { 
       Log.e("log_tag", "Error in http connection "+e.toString()); 
       } 


      //convert response to string 
    try{ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     sb.append(line + "\n"); 
     } 
     is.close(); 
     result=sb.toString(); 
      } 
      catch(Exception e){ 
      Log.e("log_tag", "Error converting result "+e.toString()); 
       } 


      return result; 
      } 
     protected void onPostExecute(String result){ 

     try{ 
      JSONArray jArray = new JSONArray(result); 
      JSONObject json_data=null; 
      for(int i=0;i<jArray.length();i++) 
      { 
       json_data = jArray.getJSONObject(i); 
       int population=json_data.getInt("City_Population"); 

       TextView City_Name =(TextView)findViewById(R.id.city_name); 
                      TextView City_population=(TextView)findViewById(R.id.city_pop); 
          City_Name.setText(json_data.getString(city_name)); 
                      City_population.setText(population+" "); 
      } 
      } 
      catch(JSONException e){ 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
      } 


        } 
                    } 

                } 
+1

聽u能告訴我在mysql中,City_Population是幫助我的工作 – Rizvan 2012-04-05 09:28:59

回答

2
 <?php 
     $name=$_POST['NAME'];    
     mysql_connect("localhost","username","password"); 
     mysql_select_db("Countries"); 
     $sql=mysql_query("select City_Population as citypop from City where Name='$name' "); 
     while($row=mysql_fetch_assoc($sql)) 
      $output=$row['citypop']; 
     print(json_encode($output)); 
     mysql_close(); 
     ?> 

你試試這個確定它會工作。

+0

感謝,因爲其新的IAM在PHP – user 2012-04-05 19:08:42

1

a)您的腳本容易出現sql injections。在將它放入sql查詢字符串之前,您需要正確編碼$ _REQUEST [...]參數。
b)你需要一些錯誤處理。任何mysql_ *函數都可能失敗,您的腳本必須處理這些錯誤情況。由於客戶端期望某些json數據只是將錯誤消息/代碼作爲json編碼數組返回。
c)你可能需要將Content-type頭設置爲application/json,看到RFC 4627http://docs.php.net/function.header

<?php 
define('DEBUG_DETAILS', true); 
function onError($msg, $details) { 
    $msg = array(
     'status'=>'error', 
     'message'=>$msg 
    ); 
    if (defined('DEBUG_DETAILS') && DEBUG_DETAILS) { 
     $msg['details'] = $details; 
    } 
    die(json_encode($msg)); 
} 


$mysql = mysql_connect("localhost","username","password") or OnError('database connection failed', mysql_error()); 
mysql_select_db("Countries", $mysql) or OnError('database selection failed', mysql_error($mysql)); 

$query = " 
    SELECT 
     City_Population 
    FROM 
     City 
    WHERE 
     Name='%s' 
"; 
$query = sprintf($query, mysql_real_escape_string($_REQUEST['Name'], $mysql)); 
$sql=mysql_query($query, $mysql) or OnError('query failed', array('query'=>$query, 'errstr'=>mysql_error($mysql))); 

$output = array(
    'count'=>0, 
    'records'=>array() 
); 
while($row=mysql_fetch_assoc($sql)) { 
    $output['records'][]=$row; 
    $output['count']+=1; 
} 
echo json_encode(array(
    'status'=>'ok', 
    'result'=>$output 
)); 

你的Android客戶端應接收對象文本象例如

{ 
    status:"ok", 
    result: { 
    'count': 2, 
    'records': [ 10000, 15000] 
    } 
} 

{ 
    status:"error", 
    message: "database connection failed", 
    setails: "...." 
} 
+0

感謝retriving或多個數據 – user 2012-04-05 19:02:44

+0

@VolkerK嘿感謝有幫助我可以使用它:) – Rizvan 2012-04-07 08:49:32