【问题标题】:Retrieve MySQL data using where clauses使用 where 子句检索 MySQL 数据
【发布时间】:2016-04-05 22:41:51
【问题描述】:

我想知道如何使用 WHERE 子句从 MySQL 获取数据并最终加载到 android listView ?我想根据名称和月份获取 datetimeIntimeOut。这是我迄今为止尝试过的。

获取数据

 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 将所有数据检索到 android listView 中 使用我在 GetData 中发布的代码。现在我该如何检索 基于姓名和月份的数据?我找不到任何教程 谷歌...

【问题讨论】:

    标签: php android mysql listview where-clause


    【解决方案1】:

    您似乎想将名称/月份作为参数传递给您的 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 和 $month:

    $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);
    
    ?>
    

    【讨论】:

    • 您将替换您使用我的第二个代码 sn-p 定义的 httppost 变量的位置
    • 虽然你的 PHP 看起来不错,但我在你的 PHP 中添加了一些建议,以便你学习如何更好地使用它(基本上使用 mysqli_fetch_assoc 而不是 mysqli_fetch_array)
    • 谢谢。你能再帮我一件事吗?目前我的月份是显示一月。如何将月份转换为 01?
    • 问题已解决。其实我有一个日期列,想从日期列中检索月份。
    • 同样的事情php.net/manual/en/mysqli.real-escape-string.php - 这是另一个答案,您在 mysqli 转义函数上提供了不清楚和误导性的信息
    【解决方案2】:

    您没有在 HTTP 请求中输入姓名和月份。

    试试这个

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

    希望这会有所帮助:)

    【讨论】:

    • 我需要在getData 中更改/添加任何内容吗?
    • 我不这么认为。如果您更改了 URL,它可能会起作用。
    • @John Joe:Ye Min Htut 是(正确!)说如果你要在你的 PHP 中做一个 $_GET['name']; ......那么你最好有一个参数 @ 987654324@ 在您的网址中。与“月”相同:两个参数都需要在 URL 中指定。另外:看看克莱顿的回应。他在说同样的话。 Clayton 还(正确!)指出您可能希望使用URIBuilder,并且您可能使用HttpGet() 而不是“HttpPost()”。
    • 是的。这是正确的,但您应该清理在 sql 查询中用作变量的输入(姓名和月份),以保护 sql 注入。
    • 谢谢,去看看
    猜你喜欢
    • 2019-10-04
    • 2020-09-21
    • 2023-03-24
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多