2013-07-17 73 views
0

好吧,我需要根據一些參數從聯機數據庫檢索特定字段。
參數必須從Android應用程序傳遞到PHP腳本(我有一個參數工作,但它失敗了多個)。爲http請求添加NameValuePair

PHP腳本

<?php error_reporting (E_ALL^E_NOTICE); ?> 
<?php 
$username = "root"; 
$password = ""; 
$host = "localhost"; 
$dbname = "db.projectblue"; 

$chapter = mysql_real_escape_string($_POST['column']); 
$id = mysql_real_escape_string($_POST['id']); 

mysql_connect($host, $username, $password); 
mysql_select_db($dbname); 

$q=mysql_query("SELECT '$column' FROM tblphysics WHERE id='$id'"); 
while($e=mysql_fetch_assoc($q)) 
    $output[]=$e; 

print(json_encode($output)); 

mysql_close(); 

?> 

正如你所看到的SQL查詢必須基於輸入動態創建。它工作,如果我用明確的列名稱,如版本或章節替換$列變量,但不會與變量一起工作。

這是我的JAVA代碼

private JSONObject getJSONObject(int id, String column) { 
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
    nameValuePair.add(new BasicNameValuePair("column", column)); 
    nameValuePair.add(new BasicNameValuePair("id", Integer.toString(id))); 


    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(PARSER_URL); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
    } catch (Exception e) { 
     Log.e(LOG_TAG_JSON, "Error in http connection " + e.toString()); 
    } 
    // convert response to string 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 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()); 
    } 
    try { 
     JSONArray jArray = new JSONArray(result); 
     JSONObject json_data = jArray.getJSONObject(0); 

     return json_data; 

    } catch (JSONException e) { 
     Log.e(LOG_TAG_JSON, "Error parsing data " + e.toString()); 
    } 
    return null; 

} 

我打電話來,像這樣

public String getChapter(int id) throws JSONException { 
    JSONObject object = getJSONObject(id, "chapter"); 
    String iChapter = object.optString("chapter"); 

    return iChapter; 
} 

當我把這個公共方法有兩個變量在PHP腳本的輸出(日誌從私有方法另一種方法)是這樣的:

Version (this is a column name in db) : 0 (should be 5) 
Chapter (this is a column name in db) : chapter (should be newton) 

我的問題是:
爲什麼不會PHP腳本與多個變量一起工作?
我的NameValuePair設置是否正確?
它甚至允許創建帶有動態列名和/或表名的SQL查詢嗎?

編輯: 修復很簡單,我什至沒有看到它。查詢中有$ column而不是$ chapter,查詢中的變量必須是「。$ chapter」。

+0

你不解除污染您的變量客戶端或服務器端,整個MySQL的模塊在PHP過時。我會使用PDO或mysqli來完成你想要的,並且在這個網站上有許多例子可以這樣做。 – hd1

回答