2014-06-23 2 views
1

그래서 나는 PHP로 안드로이드에서 mysql으로부터 데이터를 가져 오기위한 코드를 가지고 있습니다. 입력 한 "일련 번호"를 읽은 다음 특정 SN이있는 배열로 데이터를 읽고 검색합니다.PHP는 문자열, 심지어 문자열로만 검색합니다.

숫자와 영문자 (AJH871)가 혼합 된 일련 번호가있을 때까지 모든 것이 작동합니다. 특정 데이터를 검색하지 않습니다. 분명히 번호가 아닌 다른 것 (289173 등)은 작동하지 않지만 오류는 없습니다.

어떻게 해결할 수 있을까요? (여기에서의 코드가 검색되고 gettext는로 표시되는 위치이다)

class GetProductDetails extends AsyncTask<String, String, String> { 

/** 
* Before starting background thread Show Progress Dialog 
* */ 
@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    pDialog = new ProgressDialog(EditProductActivity.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 tag 
      int success; 
      try { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("SN",SN)); 

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

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

       // json success tag 
       success = json.getInt(TAG_SUCCESS); 
       if (success == 1) { 
        // successfully received product details 
        JSONArray productObj = json 
          .getJSONArray(TAG_PRODUCT); // JSON Array 

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

        // product with this pid found 
        // Edit Text 
        txtID = (EditText) findViewById(R.id.inputID); 
        txtSerial = (EditText) findViewById(R.id.inputSerial); 
        txtJenis = (EditText) findViewById(R.id.inputJenis); 
        txtMerk = (EditText) findViewById(R.id.inputMerk); 
        //txtSpec = (EditText) findViewById(R.id.inputSpec); 
        txtUser = (EditText) findViewById(R.id.inputUser); 
        txtDept = (EditText) findViewById(R.id.inputDept); 
        txtCond = (EditText) findViewById(R.id.inputCond); 

        // display product data in EditText 
        txtID.setText(product.getString(TAG_PID)); 
        txtSerial.setText(product.getString(TAG_SERIAL)); 
        txtJenis.setText(product.getString(TAG_JENIS)); 
        txtMerk.setText(product.getString(TAG_MERK)); 
        //txtSpec.setText(product.getString(TAG_SPEC)); 
        txtUser.setText(product.getString(TAG_USER)); 
        txtDept.setText(product.getString(TAG_DEPT)); 
        txtCond.setText(product.getString(TAG_COND)); 
        check = 1; 

       }else{ 
        // product with pid not found       
        check = 2; 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      if(check == 1){ 
       Toast.makeText(getApplicationContext(), "Data ditemukan",Toast.LENGTH_SHORT).show(); 
      } 
      else if(check==2){ 
       Toast.makeText(getApplicationContext(), "ID tidak ditemukan",Toast.LENGTH_SHORT).show(); 
     } 
     } 
    }); 


    return null; 
} 

//

여기 jsonparser

 public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      }   


     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "utf-8"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

//

같습니다

여기서 코드의 일부

및 여기에 PHP

이 있습니다. 조금 지저분하다면
if (isset($_GET["SN"])) { 
    $SN = $_GET['SN']; 

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

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

      $result = mysql_fetch_array($result); 

      $product = array(); 
      $product["SN"] = $result["SN"]; 
      $product["label"] = $result["label"]; 
      $product["jenis"] = $result["jenis"]; 
      $product["merk"] = $result["merk"]; 
      $product["user"] = $result["user"]; 
      $product["dept"] = $result["dept"]; 
      $product["cond"] = $result["cond"]; 
      // success 
      $response["success"] = 1; 

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

      array_push($response["products"], $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); 
    } 

//

죄송합니다.

답변

1

이 시도 :

적절한 따옴표를 SQL 쿼리

$result = mysql_query("SELECT *FROM products WHERE SN = '$SN'"); 

에에서 : 이것에

SELECT *FROM products WHERE SN = ABC123; 

:

SELECT *FROM products WHERE SN = 'ABC123'; 
+0

을해야 귀하의 경우 ='$SN' 들어 할 것입니다! stackoverflow는 uber 긴 게시물을하지 않는 나를 금지하고 있습니다! 하하. 농담. – albertdiones

+0

감사합니다! lol, 또한 내 OC-ness는 "*", "SELECT * FROM"다음에 공백을 추가하기를 원합니다. P도 – albertdiones

+1

옙, 이미 여기에서 본 순간에 제 코드에서 이미 그랬습니다. 나는 그것이 PHP 나 mysql의 공간을 놓친다면 wouldnt 작업이라고 생각했다. – user3765896

0

을 당신이 생각 SN COLUMN가 아닌 int 종류 datatype.

당신이 =(등호) 후 작은 따옴표를 사용할 필요가 varchar 또는 다른 string friendlydatatypes을 있다면.

같은

뭔가 :이 맞다면 ='searchTermHere'이 날 upvote에 트릭을

+0

네, PHP에서 문자열에 대해서도 따옴표를 넣어야한다는 것을 알지 못했다. 나는 매일 새로운 것을 배울 것 같아. 응. – user3765896