首页 > 解决方案 > 使用 volley 从 localhost mysql 通过那里的 id 获取文本或图像

问题描述

描述:

爪哇:

@Override
public void onResponse(String response) {
try {  JSONObject jsonobject = new JSONObject(response);
       JSONArray jsonarray = jsonobject.getJSONArray("name");
       JSONObject data = jsonarray.getJSONObject(0);
       String firstName = data.getString("pricewithfuel");

      textview.setText(firstName);
      } catch (JSONException e) {
      e.printStackTrace();
       }}},
new Response.ErrorListener() {
  @Override
  public void onErrorResponse(VolleyError error) {
}}){
  @Override
  protected Map<String, String> getParams() throws AuthFailureError {
  Map<String, String> params = new HashMap<>();
  params.put("id",editText.getText().toString());
    return params;
 }};
RequestQueue requestQueue = Volley.newRequestQueue(mActivity);
requestQueue.add(stringRequest);

PHP 代码

 $connect=mysqli_connect($username,$hostname,$password,$dbname);

 $id = $_POST["id"];

 $query = "SELECT title FROM products 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);

标签: phpandroidmysqlandroid-studioandroid-volley

解决方案


您只从数据库中获取标题,再次检查您的查询

SELECT title FROM products WHERE id = '$id'

从要显示数据的数据库中添加更多数据字段


推荐阅读