【问题标题】:How to get all the product categories from the mysql db via php and return json array如何通过php从mysql db中获取所有产品类别并返回json数组
【发布时间】:2013-12-13 00:46:59
【问题描述】:

我有一个安卓应用。 我想向 get_categories.php 文件发送一个获取请求。 在我想要的 get_categories.php 文件中

$query_categories        = "SELECT category_name FROM categories";

并将在该表中找到的所有类别返回到一个 json 数组中。

我该怎么做?

这是我不完整的代码:

if (!empty($_GET)) {


    $query_categories        = "SELECT category_name FROM categories";
    $success = false;

    try{
        $sth = $connection->prepare($query_categories);
        //$sth->execute(array(':user_id' => $user_id));
        //$user_items_count = $sth->rowCount();  - these are lines from other php file I've used 

        foreach($)//??

        $success = true;
    } catch (PDOException $ex) {

        $response["success"] = 0;
        $response["message"] = $ex;
        die(json_encode($response));
        $connection = null;
    }

    if($success) {
        $response["success"] = 1;
        $response["message"] = "Kylie";

        die(json_encode($response));
        $connection = null;      

    } else {
        $response["success"] = 2;
        $response["message"] = "something went wrong";
        die(json_encode($response));
        $connection = null;
    }

} else {
        $response["success"] = 3;
        $response["message"] = "Another brick in the wall";   
        echo json_encode($response);
        $connection = null;
}

稍后,在我的 Java 代码中,我该如何解码? 通常到现在为止,在我的其他 JSON 传输中,我收到了没有数组的普通 Json 对象并以这种方式读取它们:

setUserLastSeen(json.getString(TAG_USER_LAST_SEEN)); //for example.

但是我该如何解码一个数组呢?

【问题讨论】:

    标签: php android mysql json


    【解决方案1】:

    对于 php 方面,这是如何获取类别数组并制作 json 的,对于准备好的语句,这是您可以完成的方法

    $success = false;
    try {
    
      $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $success = true;
    }
    catch(PDOException $e) {
    $response["success"] = 0;
    $response["message"] = 'Connection failed: ' . $e->getMessage();
    $response["data"]=null;
    die(json_encode($response));
    }
    
    $query_categories = "SELECT category_name FROM categories";
    
    try{
    
    $sth = $sth->prepare($query_categories );
    $success = true;
    
    } catch(PDOException $e) {
    $response["success"] = 0;
    $response["message"] = 'Prepare failed: ' . $e->getMessage();
    $response["data"]=null;
    die(json_encode($response));
    }
    
    try{
    $sth->execute();
    $success = true;
    } catch(PDOException $e) {
    $response["success"] = 0;
    $response["message"] = 'Execute failed: ' . $e->getMessage();
    $response["data"]=null;
    die(json_encode($response));
    }
    
    $categories = $sth->fetchAll(PDO::FETCH_COLUMN, 0);/* fetches all categories from db */
    
    /* Output of $query_categories
    Array
    (
        [0] => cat1
        [1] => cat2
        [2] => cat3
        [3] => cat4
    )
    */
    /* json encode $query_categories 
    ["cat1","cat2","cat3","cat4"]
    */
    
    /* check if categories exist or not*/
    if(empty($categories)){
            $response["success"] = 0;
            $response["message"] = "No categories found";
            $response["data"]=null;
            die(json_encode($response));
            $connection = null; 
    
    }
    
    if($success) {
        $response["success"] = 1;
        $response["message"] = "Kylie";
        $response["data"]=$categories;
        die(json_encode($response));
        $connection = null;      
     /* output
     {"success":0,"message":"Kylie","data":["cat1","cat2","cat3","cat4"]}
     */
    } else {
        $response["success"] = 2;/* don't where you are setting success to 2*/
        $response["message"] = "something went wrong";
        $response["data"]=null;
        die(json_encode($response));
        $connection = null;
    }
    
    } else {
            $response["success"] = 3;/* don't where you are setting success to 3*/
            $response["message"] = "Another brick in the wall";  
            $response["data"]=null; 
            die(json_encode($response));
            $connection = null;
    }
    

    我不擅长java,但这里是参考How to parse a JSON and turn its values into an Array?

    /* store json string in  the_json */
    JSONObject myjson = new JSONObject(the_json);
    JSONArray the_json_array = myjson.getJSONArray("data");
    

    注意:确保在 java 端你必须从 json 检查成功 必须为 ==1 且 the_json_array 不为空

    PHP Data Objects

    【讨论】:

      【解决方案2】:

      您可以使用以下代码通过 json 获取数据,然后解码该 json 数组:

      ================================================ ==================================== 尝试 {

                  HttpClient httpclient = new DefaultHttpClient();
      
                  HttpPost httppost = new HttpPost("your webservice");
      
                  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      
                  HttpResponse res = httpclient.execute(httppost);
      
                  HttpEntity entity = res.getEntity();
      
                  is = entity.getContent();
      
                  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      
                  StringBuilder sb = new StringBuilder();
                  sb.append(reader.readLine() + "\n");
                  String line="0";
      
                  while ((line = reader.readLine()) != null)
                  {
                      sb.append(line + "\n");
                  }
                  is.close();
                  result=sb.toString();
                  Log.d("Data",""+ result);
      
              }
              catch(Exception e)
              {
                  Log.e("log_tag", "Error converting result "+e.toString());
              }
      
              String fd_ono=null;
      
      
      
              try
              {
                  JSONArray jArray = new JSONArray(result);
                  JSONObject json_data=null;
      
                  for(int i=0;i<jArray.length();i++)
                  {
                          json_data = jArray.getJSONObject(i);
                          fd_ono=json_data.getString("your column name");
                          textView.settext(fd_ono.toString());
      
      
      
                  }
      
      
              }
      
      
              catch(JSONException e1)
              {
                  Toast.makeText(getBaseContext(), "Record not found", Toast.LENGTH_LONG).show();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-17
        • 1970-01-01
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多