2011-05-19 65 views
0

目前,我檢索數據從數據庫就是這樣如何通過用戶輸入將數據插入服務器數據庫?

private void getdatafromphp(){ 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    //http post 
    try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://10.0.2.2/video.php"); 
     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,"iso-8859-1"),8); 
     sb = new StringBuilder(); 
     sb.append(reader.readLine() + "\n"); 
     String line="0"; 
     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()); 
    } 
       //paring data 
    try{ 
     jArray = new JSONArray(result); 
     JSONObject json_data=null; 
     json_data = jArray.getJSONObject(jArray.length()-1); 
     url=json_data.getString("VideoUrl"); 
    }catch(JSONException e1){ 
    }catch(ParseException e1) { 
     e1.printStackTrace(); 
    } 
} 

這個PHP

<?php 
mysql_connect("localhost","root",""); 
mysql_select_db("imammuda"); 
$sql=mysql_query("select * from Video"); 
while($row=mysql_fetch_assoc($sql)) 
$output[]=$row; 
print(json_encode($output)); 
mysql_close(); 
?> 

現在我想將數據插入到數據庫中。怎麼做?

我找到了「insert into table(column1,column2)values('value1','value2')」的sql命令。

這是插入常量值,這是在php中鍵入。

我想從java那裏得到用戶的輸入,然後將該輸入複製到php'value1'後運行php來更新數據庫。

+0

試試這個 [鏈接](http://coderzheaven.com/index.php/2011/04/android-phpmysql連接/) – 2011-05-19 07:15:17

+0

嘗試此鏈接: http://stackoverflow.com/questions/5829449/how-to-send-a-http-request-by-json-in-android/5830138#5830138 – 2011-05-19 07:17:48

回答

0

取決於您是否使用Get或Post

我將承擔GET

$value = $_GET['value']; // this will retrieve the value from the url and save it in a variable 

mysql_connect("localhost","root",""); 

// escape the value first 
$value = mysql_real_escape_string($value); 


mysql_select_db("imammuda"); 
$result = mysql_query("insert into Video (value) values ('$value')"); 

?> 

瞭解與db here

UPDATE工作

知道正確請求方法你可以使用這個。

$req; 
if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $req = $_GET; 
}else { 
    $req = $_POST; 
} 

現在你可以使用$ REQ爲您的請求變量:

$value = $req['value']; 
+0

當從數據庫中檢索,我正在使用POST – newbie 2011-05-19 07:42:42

+0

在這種情況下,只需將$ _GET替換爲$ _POST – Ibu 2011-05-19 08:33:50

+0

這是php代碼?或java? – newbie 2011-05-19 08:39:03

相關問題