2016-01-01 130 views
1

我很好奇如何使用WHERE子句從MySQL獲取數據並最終加載到android listView?我想獲得日期,timeIntimeOut根據名稱和月份。這是我到目前爲止所嘗試的。使用where子句檢索MySQL數據

的GetData

public void getData(String name, String month) { 
     class GetDataJSON extends AsyncTask<String, Void, String> { 

      @Override 
      protected String doInBackground(String... params) { 
       DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
       HttpPost httppost = new HttpPost("http://192.168.1.7/Android/CRUD/retrieveInformation.php"); 


       // Depends on your web service 
       httppost.setHeader("Content-type", "application/json"); 

       InputStream inputStream = null; 
       String result = null; 
       try { 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 

        inputStream = entity.getContent(); 
        // json is UTF-8 by default 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 
        result = sb.toString(); 
       } catch (Exception e) { 
        // Oops 
       } 
       finally { 
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
       } 
       return result; 
      } 

      @Override 
      protected void onPostExecute(String result){ 
       myJSON=result; 
       showList(); 
      } 
     } 
     GetDataJSON g = new GetDataJSON(); 
     g.execute(); 
    } 

    protected void showList(){ 
     try { 
      JSONObject jsonObj = new JSONObject(myJSON); 
      information = jsonObj.getJSONArray(Config.TAG_RESULTS); 

      for(int i=0;i<information.length();i++){ 
       JSONObject c = information.getJSONObject(i); 
       String date = c.getString(Config.TAG_DATE); 
       String timeIn = c.getString(Config.TAG_TiME_IN); 
       String timeOut = c.getString(Config.TAG_TIME_OUT); 
       HashMap<String,String> info = new HashMap<String,String>(); 
       info.put(Config.TAG_DATE, date); 
       info.put(Config.TAG_TiME_IN, timeIn); 
       info.put(Config.TAG_TIME_OUT,timeOut); 

       infoList.add(info); 
      } 

      ListAdapter adapter = new SimpleAdapter(
        HomePage.this, infoList, R.layout.retrieve_data, 
        new String[]{Config.TAG_DATE,Config.TAG_TiME_IN,Config.TAG_TIME_OUT}, 
        new int[]{R.id.date,R.id.timeIn,R.id.timeOut} 
      ); 

      listView.setAdapter(adapter); 

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

    } 

retrieveInformation.php

<?php 
    define('HOST','127.0.0.1:3307'); 
    define('USER','root'); 
    define('PASS',''); 
    define('DB','androiddb'); 

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect'); 

    $name = $_GET['name']; 

    $month = $_GET['month']; 

    $sql = "select * from information WHERE name= '". $name."' and month = '".$month."'"; 

    $res = mysqli_query($con,$sql); 

    $result=array(); 

    while($row=mysqli_fetch_array($res)){ 
     array_push($result,array('id'=>$row[0],'name'=>$row[1],'weather'=>$row[2],'date'=>$row[3],'status'=>$row[4], 
     'time_in'=>$row[5], 'time_out'=>$row[6])); 
    } 

echo (json_encode(array("result"=>$result))); 

mysqli_close($con); 

?> 

我能夠從MySQL通過 使用我已經張貼在代碼檢索所有數據到安卓listView的GetData。現在如何根據名稱和月份檢索 數據?我找不到 谷歌的任何教程...

回答

2

它看起來像你想要的名稱/月作爲參數傳遞給你的PHP文件。 你可以做最簡單的方法是通過在URL字符串傳遞參數(簡單的方法):

HttpPost httppost = new HttpPost('http://192.168.1.7/Android/CRUD/retrieveInformation.php?name=SomeName&month=SomeMonth') 

然後,名稱和月份被看作是你在你的PHP文件中有$ _GET變量。

但是,因爲你希望你的代碼進行編碼正確,你會做這樣的事情,而不是:

URI uri = new URIBuilder() 
    .setScheme("http") 
    .setHost("192.168.1.7") 
    .setPath("/Android/CRUD/retrieveInformation.php") 
    .addParameter("name", name) 
    .addParameter("month", month) 
    .build(); 
HttpGet httpget = new HttpGet(uri); 

注意,我在第二個例子中使用HttpGet而不是HttpPost

快速在你的PHP代碼的建議,所以你不必所有的索引重新映射到它們的鍵名:

while($row=mysqli_fetch_assoc($res)){ 
    $result[] = $row; 
} 

mysqli_fetch _assoc會將數組的鍵設置爲列名。這將發送所有的列。如果你不想將所有列,只有7列,您應該修改您的選擇查詢到這一點:

$sql = "select id, name, weather, date, status, time_in, time_out from information WHERE name= '". $name."' and month = '".$month."'"; 

而且,你的選擇查詢之前也消毒$ name和$月:

$name = mysqli_escape_string($name); 
$month = mysqli_escape_string($month); 

這裏是你的代碼更新,以反映修改:

<?php 
define('HOST','127.0.0.1:3307'); 
define('USER','root'); 
define('PASS',''); 
define('DB','androiddb'); 

$con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect'); 

$name = $_GET['name']; 

$month = $_GET['month']; 
$months = [ 
'January' => '01', 
'February' => '02', 
'March' => '03', 
'April' => '04', 
'May' => '05', 
'June' => '06', 
'July' => '07', 
'August' => '08', 
'September' => '09', 
'October' => '10', 
'November' => '11', 
'December' => '12', 
]; 

if (!isset($months[ $month ])) { 
    die("Invalid month"); 
} 

$month = $months[ $month ]; 


$name = mysqli_escape_string($con, $name); 
$month = mysqli_escape_string($con, $month); 
$sql = "select * from information WHERE name= '". $name."' and month = '".$month."'"; 

$res = mysqli_query($con,$sql); 

$result=array(); 

while($row=mysqli_fetch_assoc($res)){ 
    $result[] = $row; 
} 

echo (json_encode(array("result"=>$result))); 

mysqli_close($con); 

?> 
+0

我應該在哪裏添加上面的代碼? –

+0

你會替換你有我的第二個代碼段定義的'httppost'變量 – Clay

+0

我的php看起來是否正確? –

3

您沒有在您的HTTP請求中放入名稱和月份。

試試這個

HttpPost httppost = new HttpPost("http://192.168.1.7/Android/CRUD/retrieveInformation.php?name="+name+"&month="+month); 

希望這有助於:)

+0

我是否需要更改/添加在'getData'什麼? –

+0

我不這麼認爲。如果您更改了網址,它可能會有效。 –

+1

@John Joe:葉敏Htut(正確!)說如果你要在你的PHP中做一個'$ _GET ['name'];'......那麼你最好在URL中有一個參數'name = xyz'。與「月」相同:這兩個參數都需要在URL中指定。還有:看看克萊頓的迴應。他說的是同樣的事情。 Clayton也(正確的)指出你可能希望使用'URIBuilder',並且你可以使用'HttpGet()'而不是「HttpPost()」。 – paulsm4