2012-11-09 78 views
0

我遇到了一個問題,我的應用程序試圖從mysql數據庫中檢索數據。當我運行應用程序時,我收到了一條消息,表明我在php代碼中創建了「未找到學生」。 這裏是Java代碼:我無法從Mysql數據庫檢索數據到Android應用程序

public class StudentEditAccount extends Activity { 
    EditText txtsid; 
    EditText txtfirstname; 
    EditText txtlastname; 
    EditText txtcoursecode; 
    EditText txtphonenumber; 
    EditText txtemail; 

    Button btnSave; 
    Button btnDelete; 

    String sid; 

    // Progress Dialog 
    private ProgressDialog pDialog; 

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

    // single student url 
    private static final String url_product_detials = "http://10.0.2.2/example/get_product_details.php"; 

    // url to update student 
    private static final String url_update_product = "http://10.0.2.2/example/update_product.php"; 

    // url to delete student 
    private static final String url_delete_product = "http://10.0.2.2/example/delete_product.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_STUDENTS = "students"; 
    private static final String TAG_SID = "sid"; 
    private static final String TAG_FIRSTNAME = "firstname"; 
    private static final String TAG_LASTNAME = "lastname"; 
    private static final String TAG_COURSECODE = "coursecode"; 
    private static final String TAG_PHONENUMBER = "phonenumber"; 
    private static final String TAG_EMAIL = "email"; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.studenteditaccount); 

     // save button 
     btnSave = (Button) findViewById(R.id.btnSave); 
     btnDelete = (Button) findViewById(R.id.btnDelete); 

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

     // getting student id (id) from intent 
     sid = i.getStringExtra(TAG_SID); 

     // Getting complete student details in background thread 
     new GetStudentAccountDetails().execute(); 


     // save button click event 
     btnSave.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // starting background task to update student 
        new SaveStudentAccountDetails().execute(); 

      } 
     }); 

     // Delete button click event 
     btnDelete.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // deleting student in background thread 
        new DeleteStudentAccount().execute(); 

      } 
     }); 
    } 

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

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

     /** 
     * Getting student 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("sid", sid)); 

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

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

         // json success tag 
         success = json.getInt(TAG_SUCCESS); 
         if (success == 1) { 
          // successfully received student details 
          JSONArray studentsObj = json 
            .getJSONArray(TAG_STUDENTS); // JSON Array 

          // get first student object from JSON Array 
          JSONObject students = studentsObj.getJSONObject(0); 

          // student with this sid found 
          // Edit Text 
          txtfirstname = (EditText) findViewById(R.id.inputfname); 
          txtlastname = (EditText) findViewById(R.id.inputlname); 
          txtcoursecode = (EditText) findViewById(R.id.inputcoursecode); 
          txtphonenumber = (EditText) findViewById(R.id.inputphonenumber); 
          txtemail = (EditText) findViewById(R.id.inputemail); 



          // display student data in EditText 
          txtfirstname.setText(students.getString(TAG_FIRSTNAME)); 
          txtlastname.setText(students.getString(TAG_LASTNAME)); 
          txtcoursecode.setText(students.getString(TAG_COURSECODE)); 
          txtphonenumber.setText(students.getString(TAG_PHONENUMBER)); 
          txtemail.setText(students.getString(TAG_EMAIL)); 


         }else{ 
          // student with sid 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(); 
     } 
    } 

    /** 
    * Background Async Task to Save student Details 
    * */ 
    class SaveStudentAccountDetails extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(StudentEditAccount.this); 
      pDialog.setMessage("Saving account ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Saving student 
     * */ 
     protected String doInBackground(String... args) { 

      // getting updated data from EditTexts 
      String sid = txtsid.getText().toString(); 
      String firstname = txtfirstname.getText().toString(); 
      String lastname = txtlastname.getText().toString(); 
      String coursecode = txtcoursecode.getText().toString(); 
      String phonenumber = txtphonenumber.getText().toString(); 
      String email = txtemail.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair(TAG_SID, sid)); 
      params.add(new BasicNameValuePair(TAG_FIRSTNAME, firstname)); 
      params.add(new BasicNameValuePair(TAG_LASTNAME, lastname)); 
      params.add(new BasicNameValuePair(TAG_COURSECODE, coursecode)); 
      params.add(new BasicNameValuePair(TAG_PHONENUMBER, phonenumber)); 
      params.add(new BasicNameValuePair(TAG_EMAIL, email)); 

      // sending modified data through http request 
      // Notice that update student url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest(url_update_product, 
        "POST", params); 

      // check json success tag 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // successfully updated 
        Intent i = getIntent(); 
        // send result code 100 to notify about student update 
        setResult(100, i); 
        finish(); 
       } else { 
        // failed to update student 
       } 
      } 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 student updated 
      pDialog.dismiss(); 
     } 
    } 

    /***************************************************************** 
    * Background Async Task to Delete Product 
    * */ 
    class DeleteStudentAccount extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(StudentEditAccount.this); 
      pDialog.setMessage("Deleting Account..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Deleting student 
     * */ 
     protected String doInBackground(String... args) { 

      // Check for success tag 
      int success; 
      try { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("sid", sid)); 

       // getting student details by making HTTP request 
       JSONObject json = jsonParser.makeHttpRequest(
         url_delete_product, "POST", params); 

       // check your log for json response 
       Log.d("Delete student", json.toString()); 

       // json success tag 
       success = json.getInt(TAG_SUCCESS); 
       if (success == 1) { 
        // student successfully deleted 
        // notify previous activity by sending code 100 
        Intent i = getIntent(); 
        // send result code 100 to notify about student deletion 
        setResult(100, i); 
        finish(); 
       } 
      } 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 student deleted 
      pDialog.dismiss(); 

     } 

    } 
} 

這是PHP代碼:

<?php 

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

// include db connect class 
require_once __DIR__ . '/db_connect.php'; 

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

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

    // get a students from student table 
    $result = mysql_query("SELECT *FROM student WHERE sid = $sid"); 

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

      $result = mysql_fetch_array($result); 

      $students = array(); 
      $students["sid"] = $result["sid"]; 
      $students["firstname"] = $result["firstname"]; 
      $students["lastname"] = $result["lastname"]; 
      $students["coursecode"] = $result["coursecode"]; 
      $students["phonenumber"] = $result["phonenumber"]; 
      $students["email"] = $result["email"]; 
      // success 
      $response["success"] = 1; 

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

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

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

      // echo no users JSON 
      echo json_encode($response); 
     } 
    } else { 
     // no student found 
     $response["success"] = 0; 
     $response["message"] = "No student 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); 
} 
?> 

我的問題是:什麼是導致應用程序顯示消息的問題「學生未找到」每當我嘗試從Mysql數據庫檢索數據? 謝謝。

回答

0

SQL查詢中缺少空格。它應該是SELECT * FROM student WHERE sid = $sid

+0

謝謝你的回覆,我把空間放在那個SQL查詢中,我仍然得到這條消息:學生找不到。 – Mack

+0

檢查你的查詢是否絕對好。理想情況下,你從php輸出精確的查詢,然後用數據庫客戶端對數據庫執行它。兩種可能性:1.你的sid不正確,或者2.這個sid沒有輸入。 – SimonSays

相關問題