Reputation: 399
I am trying to get data from MySQL database to my android app using where condition. I already create a method for get data. This method give me all data as a string array from a single column. Look the bellow method :
String adress = "http://myserver_link/get_data.php";
InputStream inputStream = null;
String line = null, result = null, data[];
private void get_data(){
try {
URL url = new URL(adress);
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(httpsURLConnection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// read input stream into a string
try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
// Parse json data
try{
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = null;
data = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("user_adress"); // column name
}
}
catch (Exception e){
e.printStackTrace();
}
}
This is my get data java method. And my get_data.php code is :
<?php
require "conn.php";
$query = mysqli_query($conn, "select * from android_data");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
Now I want to write my get_data.php file like bellow :
<?php
require "conn.php";
$user_name = $_POST["username"];
$query = mysqli_query($conn, "select * from android_data where username='$user_name'");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
But how I can send username using get_data() java method from my app?
Upvotes: 2
Views: 5168
Reputation: 57121
You should probably send this as a parameter on the URL...
String adress = "http://myserver_link/get_data.php?username=xxxxx";
Not done Java for a while, but you can create this string using the appropriate value for xxxxx.
This will then be passed in as $_GET["username"]
instead of $_POST["username"]
. So just replace this line
$user_name = $_POST["username"];
with
$user_name = $_GET["username"];
Upvotes: 2