2013-02-26 50 views
0

我想選擇在MySQL中的行值。 當我運行的代碼時,logcat的節目「必填字段(一個或多個)丟失」。 我不知道在PHP或Android代碼的問題。 我希望有人能幫助我。爲什麼PHP不能得到的價值?在android系統到PHP

public class profileActivity extends Activity{ 


EditText txtName; 
EditText inputusername; 
EditText answer; 
EditText txtPrice; 
EditText txtDesc; 
EditText txtCreatedAt; 
String username; 

private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_UID = "uid"; 
private static String KEY_NAME = "name"; 
private static String KEY_FIRSTNAME = "first_name"; 
private static String KEY_lASTNAME = "last_name"; 
private static String KEY_EMAIL = "email"; 



private DatabaseHandler dbHelper; 
private ProgressDialog pDialog; 

// JSON parser class 
JSONParser jsonParser = new JSONParser(); 

// single product url 
private static final String profileURL =  "http://10.0.2.2/android_login_api4/include/profile.php"; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.profile);  

// getting product details from intent 
     Intent i = getIntent(); 

     // getting product id (pid) from intent 
     username = i.getStringExtra(KEY_NAME); 


    // Getting complete product details in background thread 
    new GetProfileDetails().execute(); 

} 



/** 
* Background Async Task to Get complete product details 
* */ 
class GetProfileDetails extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(profileActivity.this); 
     pDialog.setMessage("Loading product details. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 


     /** 
     * Getting product details in background thread 
     * */ 
     protected String doInBackground(String... params) { 

      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        // Check for success KEY 
        int success; 
        try { 


         // Building Parameters 
         List<NameValuePair> params = new ArrayList<NameValuePair>(); 
         params.add(new BasicNameValuePair("username", username)); 

         // getting product details by making HTTP request 
         // Note that product details url will use GET request 
         JSONObject json = jsonParser.getJSONFromUrl(
           profileURL, params); 

         // check your log for json response 
         Log.d("Single Product Details", json.toString()); 

         // json success KEY 
         success = json.getInt(KEY_SUCCESS); 
         if (success == 1) { 
          // successfully received product details 
          JSONArray productObj = json 
            .getJSONArray(KEY_NAME); // JSON Array 

          // get first product object from JSON Array 
          JSONObject product = productObj.getJSONObject(0); 

          // product with this uid found 
          // Edit Text 
          txtName = (EditText) findViewById(R.id.name); 
          txtPrice = (EditText) findViewById(R.id.email); 
          txtDesc = (EditText) findViewById(R.id.tel); 

          // display product data in EditText 
          txtName.setText(product.getString(KEY_lASTNAME)); 
          txtPrice.setText(product.getString(KEY_FIRSTNAME)); 
          txtDesc.setText(product.getString(KEY_EMAIL)); 

         }else{ 
          // product with uid not found 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once got all details 
      pDialog.dismiss(); 
     } 
    } 
} 

這是PHP

<?php 

// array for JSON response 
$response = array(); 


// include db connect class 
require_once 'DB_Connect.php'; 

// connecting to db 
$db = new DB_CONNECT(); 

// check for post data 
if (isset($_GET["username"])) { 
$username = $_GET['username']; 

// get a product from products table 
$result = mysql_query("SELECT *FROM users WHERE username = $username"); 

if (!empty($result)) { 
    // check for empty result 
    if (mysql_num_rows($result) > 0) { 

     $result = mysql_fetch_array($result); 

     $product = array(); 
     $product["username"] = $result["username"]; 
     $product["first_name"] = $result["first_name"]; 
     $product["last_name"] = $result["last_name"]; 
     $product["email"] = $result["email"]; 
     $product["tel"] = $result["tel"]; 
     $product["age"] = $result["age"]; 
     // success 
     $response["success"] = 1; 

     // user node 
     $response["product"] = array(); 

     array_push($response["product"], $product); 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 
     // no product found 
     $response["success"] = 0; 
     $response["message"] = "No product found"; 

     // echo no users JSON 
     echo json_encode($response); 
    } 
} else { 
    // no product found 
    $response["success"] = 0; 
    $response["message"] = "No product found"; 

    // echo no users JSON 
    echo json_encode($response); 
} 
} else { 
// required field is missing 
$response["success"] = 0; 
$response["message"] = "Required field(s) is missing"; 

// echoing JSON response 
echo json_encode($response); 
} 
?> 
+0

我假設'$ username'是一個字符串?它必須在查詢中引用爲''$ username''_ _ _ _ _ _ _ _ _ _ _ _之後,您已經調用_'mysql_real_escape_string()'來防止sql注入。 – 2013-02-26 13:56:57

+0

如果你纔剛剛開始這個項目,它是不是太晚了改變。不要使用'mysql_query()'及其親屬,而應考慮切換到支持預備語句(如[PDO](http://php.net/manual/en/book.pdo.php)或MySQLi)的API。使用得當,他們更安全。 – 2013-02-26 14:02:51

回答

0

代碼可以通過在瀏覽器中打開這個網址檢查你的PHP代碼。

http://10.0.2.2/android_login_api4/include/profile.php?username=username 

請確保您在URL的末尾放置了正確的用戶名。

如果你的PHP代碼是正確的,它會顯示你到別的一個JSON格式化文本,如果你會顯示一個錯誤,這樣你可以找到你的PHP代碼是正確或不正確的。

+0

謝謝你的方式 我覺得PHP CODE有一些問題 – 2013-02-26 16:03:37

0

我覺得你的問題是,你的代碼不給參數的屬性格式方式的服務器。

這是我簡單的例子,我該怎麼辦這種溝通:

private static String convertStreamToString(InputStream IS) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(IS)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      IS.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

private JSONObject processCommand(String command, String params) { 
    JSONObject result = null; 

    HttpClient client = new DefaultHttpClient(); 
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); 
    HttpResponse response; 

    try{ 
     String s = serverURL + command + ".php"; 
     if (params.length() != 0) s += "?" + params; 

     Log.v("Wordster", s); 

     HttpGet get = new HttpGet(s); 
     response = client.execute(get); 

     if (response != null){ 
      InputStream instream = response.getEntity().getContent(); 

      String instring = convertStreamToString(instream); 

      Log.v("Wordster", instring); 

      JSONObject json = new JSONObject(instring); 
      instream.close(); 

      result = json; 
     } 
    } catch(Exception e) { 
     e.printStackTrace(); 
     result = null; 
    } 

    return result; 
} 


public CommandResult getUserProfile(int userId) { 
    String paramstr = 
      "sessionid=" + sessionID + 
      "&userid=" + userId; 

    JSONObject data = processCommand("getuserprofile", paramstr); 

    if (data != null) { 
     try { 
      if (data.getString("result").equals("ok")) { 

       JSONObject u = data.getJSONObject("data"); 

       User user = new User(
         u.getInt("userid"), 
         u.getString("loginname"), 
         u.getString("username"), 
         u.getString("email"), 
         u.getString("sex"), 
         AXUtils.convertSQLStringToDate(u.getString("birthdate")) 
       ); 

       return new CommandResult(ResultCodes.OK, user); 
      } else { 
       if (data.getInt("errcode") == -2) 
        return new CommandResult(ResultCodes.ERR_INVALID_SESSION); 
       else 
        return new CommandResult(ResultCodes.ERR_INTERNAL); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    return new CommandResult(ResultCodes.ERR_COMM_ERROR); 
} 

,並從活動的用法如下:

private void loadUserProfile() { 
    AsyncTask<Integer, Void, CommandResult> load = new AsyncTask<Integer, Void, CommandResult>() { 
     @Override 
     protected CommandResult doInBackground(Integer... userId) { 
      WordsterApp app = (WordsterApp) getApplication(); 
      return app.server.getUserProfile(userId[0]); 
     } 

     @Override 
     protected void onPostExecute(CommandResult result) { 
      User u = (User) result.data; 
      if (u != null) { 
       user = u; 

       findViewById(R.id.ControlsLayout).setVisibility(View.VISIBLE); 
       findViewById(R.id.LoadingLayout).setVisibility(View.GONE); 

       EditText et = (EditText) findViewById(R.id.LoginNameEditText); 
       et.setText(user.loginName); 
       et = (EditText) findViewById(R.id.UserNameEditText); 
       et.setText(user.userName); 
       et = (EditText) findViewById(R.id.EmailEditText); 
       et.setText(user.email); 
       et = (EditText) findViewById(R.id.BirthDateEditText); 
       et.setText(AXUtils.ConvertDateToString(getBaseContext(), user.birthDate));   
      } else { 
       new AXErrDialog(UserProfileActivity.this, R.string.cannot_communicate_with_server) { 
        @Override 
        void onClosed() { 
         setResult(Activity.RESULT_CANCELED); 
         finish(); 
        }; 
       }.Show(); 
      } 
     } 
    }; 

    load.execute(userID); 
} 

而且PHP代碼是(getuserprofile.php ):

require_once("../config.php"); 
require_once(LIBSDIR."db.class.php"); 
require_once(LIBSDIR."xutils.php"); 
require_once(LIBSDIR."ws_base.php"); 

if (!isset($_REQUEST["sessionid"]) || !isset($_REQUEST["userid"])) { 
    Error(-1); 
} 

$sessionid = $_REQUEST["sessionid"]; 
$userid = $_REQUEST["userid"]; 

$db = new DataBase(DB_SERVER, DB_DATABASE, DB_USER, DB_PASSWORD); 

if (!$uid = CheckSessionID($db, $sessionid)) { 
    Error(-2); 
} 

if ($userid == -1) 
    $userid = $uid; 

$ds = $db->query(
    "SELECT " . 
    " nID as userid, " . 
    " cLoginName as loginname, " . 
    " cUserName as username, " . 
    " cEmail as email, " . 
    " cSex as sex, " . 
    " dBirth as birthdate, " . 
    " cProfilePictureID as profilepictureid " . 
    "FROM WS_Users " . 
    "WHERE " . 
    " nID = $userid"); 

$details = mysql_fetch_array($ds, MYSQL_ASSOC); 

$data = array(
    "result" => "ok", 
    "data" => $details 
); 

echo json_encode($data); 
+0

它是直接連接服務器嗎? 有任何PHP代碼可以幫助我嗎? – 2013-02-26 16:02:53

+0

是的,上面添加了php代碼 – 2013-02-26 21:12:48