I am developing an app that will be storing to and reading data from MySQL
db. At the moment I am able to successfully fetch 1 row
but when I am trying to fetch multiple rows
it doesn't work. To communicate with my db
I am using the volley library
.
Here is my code so far:
ResponceListener
private void getDataFromExternalDB(final String startid){
id = Integer.parseInt(startid);
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
while (jsonResponse.getJSONObject(""+id) != null){
jsonResponse.getJSONObject(""+id);
int user_id = jsonResponse.getInt("user_id");
String username = jsonResponse.getString("username");
Log.d("getDataFromExternalDB","user_id="+user_id + " username="+username);
id++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DataRequest dataRequest = new DataRequest (startid, responseListener);
RequestQueue queue = Volley.newRequestQueue(DataActivity.this);
queue.add(dataRequest );
}
DataRequest.java
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class DataRequest extends StringRequest {
private static final String DATA_REQUEST_URL = "http://192.168.178.17/getData.php";
private Map<String, String> params;
public DataRequest (String startid, Response.Listener<String> listener) {
super(Method.POST, DATA_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("startid", startid);
}
@Override
public Map<String, String> getParams() {
return params;
}
}
getData.php
<?php
$connect = mysqli_connect("localhost", "root", "pass", "db");
$startid = $_POST["startid"];
function getData() {
global $connect, $startid;
$result = $connect->query("SELECT * FROM users WHERE user_id > " . $startid );
$responses = array();
$response = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$response["user_id"] = $row["user_id"];
$response["username"] = $row["username"];
$responses["" . $row["user_id"]]=$response;
}
echo json_encode($responses);
}else {
echo "0 results";
}
}
getData();
$connect->close();
?>