fekra
fekra

Reputation: 405

Fetching data from more tahn one table in MySql Android

I want to display more than one table from mysql in android app i used this php code to display one table

PHP

<?php
include 'config1.php';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$conn->query("SET NAMES utf8");
$conn->query("SET CHARACTER SET utf8");

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 


$sql = "SELECT * FROM table1 ORDER BY id DESC";
$result = $conn->query($sql);

if ($result->num_rows >0) {
   // output data of each row
   while($row[] = $result->fetch_assoc()) {

      $tem = $row;
      $json = json_encode($tem,JSON_UNESCAPED_UNICODE);
   }

} else {
   echo "0 results";
}

echo $json;
$conn->close();

?>

How i can use this code to display more than one table

Edit: I want php code work with this Android code

MainActivity

 public void JSON_DATA_WEB_CALL(){

    Intent intent = getIntent();
    story_type = intent.getStringExtra("Story_Type");


    String GET_JSON_DATA_HTTP_URL = "http://i-geeky.info/android/" + story_type + ".php";

    jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,

            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    progress_layout.setVisibility(View.GONE);

                    JSON_PARSE_DATA_AFTER_WEBCALL(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(jsonArrayRequest);
}

public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){

    for(int i = 0; i<array.length(); i++) {

        ListItem_Rewayat GetDataAdapter2 = new ListItem_Rewayat();

        JSONObject json = null;
        try {
            json = array.getJSONObject(i);

            GetDataAdapter2.setId(json.getString(id));

            GetDataAdapter2.setName(json.getString(name));

            GetDataAdapter2.seturl(json.getString(url));

            GetDataAdapter2.setimg(json.getString(img));

            GetDataAdapter2.setnum(json.getString(num));

            GetDataAdapter2.setsize(json.getString(size));

        } catch (JSONException e) {

            e.printStackTrace();
        }
        GetDataAdapter1.add(GetDataAdapter2);

    }

    recyclerViewadapterRewayat = new Adapter_Rewayat(GetDataAdapter1, this);


    //RecyclerView needs a layout manager in order to display data so here we create one
    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

    //Here we set the layout manager and the adapter to the listview
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(recyclerViewadapterRewayat);



}

ListItem

public class ListItem_Rewayat {

public String id;
public String name;
public String url;
public String img;
public String num;
public String size;


public String getName() {

    return name;
}

public void setName(String name) {

    this.name = name;
}

public String getid() {

    return id;
}

public void setId(String id1) {

    this.id = id1;
}


public String geturl() {

    return url;
}

public void seturl(String url1) {

    this.url = url1;
}

public String getimg() {

    return img;
}

public void setimg(String img1) {

    this.img = img1;
}

public String getnum() {

    return num;
}

public void setnum(String num1) {

    this.num = num1;
}
public String getsize() {

    return size;
}

public void setsize(String size1) {

    this.size = size1;
}

}

Upvotes: 2

Views: 81

Answers (1)

Jeff
Jeff

Reputation: 6953

It's a bit of a guess, but I think this is what you want:

//...
$table1 = Array();
$table2 = Array();
$sql = "SELECT * FROM table1 ORDER BY id DESC";
$result = $conn->query($sql);

if ($result->num_rows >0) {
  // get the result for first table and save it into an array ($table1)
  while($row = $result->fetch_assoc()) {
     $table1[] = $row;
  }
} else {
  echo "0 results";
}

// just do the same for any other table
$sql = "SELECT * FROM table2 ORDER BY id DESC";
$result = $conn->query($sql);

if ($result->num_rows >0) {
  while($row = $result->fetch_assoc()) {
     $table2[] = $row;
  }
} else {
  echo "0 results";
}
// here you put together what you wanna return:
$return = Array('table1' => $table1, 
                'table2' => $table2);
// encode it
$json = json_encode($return,JSON_UNESCAPED_UNICODE);

echo $json;

BUT:
It would be better to encapsulate that into a function:

//...
function getTable($conn, $tableName) {
    $sql = "SELECT * FROM $tableName ORDER BY id DESC";
    $result = $conn->query($sql);
    $tableResult = Array();

    if ($result->num_rows >0) {
       while($row = $result->fetch_assoc()) {
          $tableResult[] = $row;
       }
    }
    return $tableResult;
}

$return = Array('table1' => getTable($conn, 'table1'), 
                'table2' => getTable($conn, 'table2')
          );
$json = json_encode($return,JSON_UNESCAPED_UNICODE);

echo $json;

Finally: There are many db-classes available for free that do stuff like that for you. Also you might want to have a look at REST-API Kitss, which are also easy to find - and for free. You are doing work, that has been done a lot of times - and most of them better and more secure. But it's good to do it again if you're still learning.

Upvotes: 1

Related Questions