2013-12-13 41 views
2

其實我是新來的android web服務,所以請幫我 我的問題我從移動客戶端發送json編碼的數據,我在服務器端獲取json數據,以便 客戶端端代碼:如何提取json數據並在mysql中插入php

mJobject.put("userName", contactname.getText().toString()); 
        mJobject.put("phonenumber",phonenumber.getText().toString()); 
        mJArray.put(mJobject); 
        Log.v(Tag, "^============send request" + mJArray.toString()); 
        contactparams.add(new BasicNameValuePair("contactdetails", mJArray.toString())); 
        Log.v(Tag, "^============send request params" + mJArray.toString()); 
        jsonString=WebAPIRequest.postJsonData("http://localhost/contactupload/contactindex.php",contactparams); 
public static String postJsonData(String url, List<NameValuePair> params) { 
    String response_string = new String(); 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
// httppost.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
    try { 
      httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 


      /* String paramString = URLEncodedUtils.format(params, HTTP.UTF_8); 
      String sampleurl = url + "" + paramString; 
      Log.e("Request_Url", "" + sampleurl);*/ 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 
      if (response != null) { 
        InputStream in = response.getEntity().getContent(); 
        response_string = WebAPIRequest.convertStreamToString(in); 

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

    return response_string; 

和PHP方面我做

<?php 
$json_data=$_POST['contactdetails']; 
$data=json_decode($json_data); 
print_r($data); 
?> 

我得到響應

Array 
(
    [0] => stdClass Object 
    (
      [phone number] => 5555 
      [username] => xfg 
    ) 
) 

所以我怎麼能提取PHP JSON數據和在mysql中插入

回答

1

不要服用點這樣的..

<?php 
$json_data=$_POST['contactdetails']; 
$data=json_decode($json_data, true); // Added true flag 

// You can access your variables like this.. 
echo $data['phone number'];// prints "5555" 
echo $data['username']; // prints "xfg" 

//do your db connection... 

// execute your query with those variables... 

?> 
0

這裏是一個示例代碼

我假設你知道如何解析JSON從android。 現在在你的服務器代碼中使用這個來從URL中的數據,並把它們插入到mysql

// check for required fields 
if (isset($_POST['location']) && isset($_POST['email']) && isset($_POST['lat']) &&  isset($_POST['longitude'])) { 

$location = $_POST['location']; 
$email = $_POST['email']; 
$lat = $_POST['lat']; 
$longitude = $_POST['longitude']; 

require_once 'config.php'; 
// connecting to mysql 
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); 
// selecting database 
mysql_select_db(DB_DATABASE); 

// mysql inserting a new row 
$result = mysql_query("INSERT INTO marked_locations(location, email,lat,longitude) VALUES('$location', '$email', '$lat','$longitude')"); 
    ..... 
    .. 

,如果您有任何doughts或有需要更多的幫助,只是評論

+0

PHP端我收到注:未定義指數當我檢索發佈數據 – skyshine

+0

您的url變量名稱必須與您通過json從android傳遞的名稱完全相同 –