2013-10-24 68 views
0

嘿im試圖從我的android應用程序發送數據到web服務器並使用mysql將它發送到數據庫,雖然它似乎沒有任何錯誤,但我的代碼沒有工作使用json從android發送數據到php

Android的Java代碼:

     String categorys=category.getText().toString(); 
      String authors = author.getText().toString(); 
      String quess = question.getText().toString(); 
      String anss = answer.getText().toString();  

        try { 
         JSONObject json = new JSONObject(); 
         json.put("category",categorys); 
         json.put("ques",quess); 
         json.put("ans",anss); 
         json.put("authors",authors); 
         postData(json); 


        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      });  
     } 

     public void postData(JSONObject json) throws JSONException { 
      HttpClient httpclient = new DefaultHttpClient(); 

      try { 
       HttpPost httppost = new HttpPost("http://shlomo.webuda.com/androidtomy.php"); 

       List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);  
       nvp.add(new BasicNameValuePair("json", json.toString())); 
       //httppost.setHeader("Content-type", "application/json"); 
       httppost.setEntity(new UrlEncodedFormEntity(nvp)); 
       HttpResponse response = httpclient.execute(httppost); 

       if(response != null) { 
        InputStream is = response.getEntity().getContent(); 
        //input stream is response that can be shown back on android 
       } 

      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 




       }` 

PHP代碼

mysql_connect("something","something","something"); 
mysql_select_db("something"); 
$json = $_SERVER['HTTP_JSON']; 
echo "JSON: \n"; 
var_dump($json); 
echo "\n\n"; 

$data = json_decode($json,true); 
var_dump($data); 




$category=$data['category']; 
$author=$data['authors']; 
$question=$data['ques']; 
$answer=$data['ans']; 
$sql = 'INSERT INTO Ques(Ques_Author, Ques_Question,Ques_Answer,Ques_Category,Ques_Approve) values("category","author","question","answer","0")'; 
mysql_query($sql); 

}  

>

+0

定義副本「不工作」 – njzk2

+0

沒有進入數據庫,插入查詢什麼也沒有發送.. –

+1

當你的值被命名爲'json'並且是一個POST變量時,你期待'$ _SERVER ['HTTP_JSON']'做什麼?不應該只是'$ _POST ['json']'? – njzk2

回答

0

正如註釋中所述,PHP文件有幾個問題。試試下面的代碼:

mysql_connect("something","something","something"); 
mysql_select_db("something"); 


$json = $_REQUEST['json']; 
echo "JSON: \n"; 
var_dump($json); 
echo "\n\n"; 

$data = json_decode($json,true); 
var_dump($data); 

$category=$data['category']; 
$author=$data['authors']; 
$question=$data['ques']; 
$answer=$data['ans']; 
$sql = "INSERT INTO Ques(Ques_Author, Ques_Question,Ques_Answer,Ques_Category,Ques_Approve) values($category,$author,$question,$answer,0)"; 
mysql_query($sql); 

另外你不應該使用mysql_query函數。您應該使用mysqli_ * *函數或PDO(http://php.net/manual/en/book.pdo.php)。有一個很好的理由,從PHP5.5開始不推薦使用mysql_query。特別是當你發佈似乎是一個正確的網址到上面的php文件。

如果您仍然有問題,請提供$ JSON-變量的內容,並從你的Java代碼的要求

+0

它仍然不起作用:\ –

+0

好吧,如果您需要我們能夠回答您將需要提供PHP json變量的內容outputtet和從請求到PHP服務器的副本。 – user2849406