【问题标题】:Android Volley: select data from MySQL database by id specified by userAndroid Volley:通过用户指定的 id 从 MySQL 数据库中选择数据
【发布时间】:2017-10-04 13:13:56
【问题描述】:

我正在使用 Volley 编写一个简单的 Android 应用程序。我想知道如何通过 ID 从 MySQL 数据库中选择名字和姓氏,哪个用户在应用程序中输入了 editText。这是我的 PHP 脚本:

 <?php
    include 'connection.php';

    global $connect;
    $id = $_POST["id"];

    $query = "SELECT firstName, lastName FROM users WHERE id = '$id'";

    $result = mysqli_query($connect, $query);
    $number_of_rows = mysqli_num_rows($result);

    $response = array();

    if($number_of_rows > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            $response[] = $row;
        }
    }

    header('Content-Type: application/json');
    echo json_encode(array("users"=>$response));
    mysqli_close($connect);

?>

如果我在代码中指定了 ID,它会返回我要求的 JSON 格式的数据,所以脚本和数据库都可以。我得到 $id=1 的响应是:

{"users":[{"firstName":"Jonash","lastName":"Corvin"}]}

这是我的 StringRequest 代码:

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try {
            JSONArray jsonArray = new JSONArray(response);
            JSONObject jsonObject = jsonArray.getJSONObject(0);

            String firstName = jsonObject.getString("firstName");
            String lastName = jsonObject.getString("lastName");

            firstNameTV.setText(firstName);
            lastNameTV.setText(lastName);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(MainActivity.this, "Something went wrong",Toast.LENGTH_LONG).show();
        error.printStackTrace();
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> parameters = new HashMap<String, String>();
        parameters.put("id", idEditText.getText().toString());
        return parameters;
    }
    };
queue.add(stringRequest);

不幸的是,它没有做任何事情......它甚至没有显示任何错误或 toast 消息。你知道怎么解决吗?

【问题讨论】:

  • 请分享您收到的 JSON 响应。
  • 我添加了。变量名有一点点错误(为了更清楚,我匆忙更改了名称),但这不是原因。
  • 您的 JSON 解析错误。 @Corgan
  • 嗯,你能告诉我到底出了什么问题吗?我按照我在其中一个 YT 教程中看到的相同方式完成了它,并且它工作正常。
  • 检查我的答案

标签: java php android mysql android-volley


【解决方案1】:

在您的 PHP 代码中将 $connect 更改为 $conn,这将解决您的问题

<?php
    include 'connection.php';

    global $connect;
    $id = $_POST["id"];

    $query = "SELECT firstName, lastName FROM users WHERE id = '$id'";

    $result = mysqli_query($conn, $query);  //<--------change
    $number_of_rows = mysqli_num_rows($result);

    $response = array();

    if($number_of_rows > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            $response[] = $row;
        }
    }

    header('Content-Type: application/json');
    echo json_encode(array("users"=>$response));
    mysqli_close($conn);  //<--------change

?>

【讨论】:

    【解决方案2】:
         StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_TRANSACTION_DETAILS,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                progressDialog.dismiss();
                                Log.i(TAG,response.toString());
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String success = jsonObject.getString("success");
                                    JSONArray jsonArray = jsonObject.getJSONArray("read");
    
                                    if (success.equals("1")) {
                                        Toast.makeText(Activity.this,"Data Fetched!",Toast.LENGTH_SHORT).show();
                                        for (int i = 0; i < jsonArray.length(); i++) {
    
                                            JSONObject object = jsonArray.getJSONObject(i);
    
                                        String firstName= object.getString("firstName").trim();
                                        String lastName= object.getString("lastName").trim();
                                        }
    }
    catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(Activity.this,"Json Login Error " +e.toString(), Toast.LENGTH_SHORT).show();
                            }}},
    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(Activity.this,"Volley Login Error " +error.toString(), Toast.LENGTH_SHORT).show();
    
                        }
                    })
    
            {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("id", id);
                    return params;
                }
            };
    

    【讨论】:

    • 通常解释你的代码是一个非常好的做法,而不仅仅是粘贴代码作为答案。
    【解决方案3】:
      <?php
        if ($_SERVER['REQUEST_METHOD']=='POST') {
            $id = $_POST['id'];
            require_once 'connection.php'
            $sql = "SELECT firstName, lastName FROM users WHERE id='$id' ";
            $response = mysqli_query($conn, $sql);
            $result = array();
            $result['read'] = array();
            if( mysqli_num_rows($response) === 1 ) {      
                if ($row = mysqli_fetch_assoc($response)) {
                     $h['firstName']        = $row['firstName'] ;
                     $h['lastName']       = $row['lastName'] ;
                     array_push($result["read"], $h);
                     $result["success"] = "1";
                     echo json_encode($result);
                }
           }
         }else {
             $result["success"] = "0";
             $result["message"] = "Error!";
             echo json_encode($result);
             mysqli_close($conn);
         }
         ?>
    

    【讨论】:

      【解决方案4】:

      {"users":[{"firstName":"Jonash","lastName":"Corvin"}]}

      根据给定的 JSON,您需要像这样解析 JSON:

      JSONObject jsonobject = new JSONObject(response);
      JSONArray jsonarray = jsonobject.getJSONArray("users");
      JSONObject data = jsonArray.getJSONObject(0);
      
      String firstName = data.getString("firstName");
      String lastName = data.getString("lastName");
      

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 2015-03-16
        • 1970-01-01
        • 2016-07-14
        • 2018-01-18
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 2016-07-23
        相关资源
        最近更新 更多