我正在开发Android应用。有一个带有ListView的片段。 我正在使用从远程服务器上的PHP文件接收的JSON数据填充ListView。
这是代码:
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(),"Fetching Data","Wait...",false,false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
Log.d("URL", "URL_GET_ALL: " + s );
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
这是远程PHP文件:
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM tb_direcciones";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id_address"=>$row['id_address'],
"cia"=>$row['cia'],
"fn"=>$row['fn'],
"ln"=>$row['ln'],
"ad1"=>$row['ad1'],
"ad2"=>$row['ad2'],
"type"=>$row['type'],
"city"=>$row['city'],
"state"=>$row['state'],
"zip"=>$row['zip'],
"phone"=>$row['phone'],
"ext"=>$row['ext'],
"fromto"=>$row['fromto'],
"user"=>$row['user']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
这部分工作正常。
现在我想过滤数据库表中的行。 片段中有一个名为MyId的String变量。我需要过滤字段用户等于MyId的行。
如何更改将MyId作为param传递给PHP文件的请求?
EDITED
RequestHandler类:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class RequestHandler {
//Method to send httpPostRequest
//This method is taking two arguments
//First argument is the URL of the script to which we will send the request
//Other is an HashMap with name value pairs containing the data to be send with the request
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public String sendGetRequest(String requestURL){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s+"\n");
}
}catch(Exception e){
}
return sb.toString();
}
public String sendGetRequestParam(String requestURL, String id){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s+"\n");
}
}catch(Exception e){
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
答案 0 :(得分:1)
您sholud将用户ID作为参数传递给查询。您可以将其作为GET参数或POST参数传递。以下示例适用于GET,当值为整数时,这是正常的。
Android应用代码:
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(String.format("%s&myid=&d", Config.URL_GET_ALL, (int)myID) );
Log.d("URL", "URL_GET_ALL: " + s );
return s;
}
PHP代码:
//Creating sql query
$sql = "SELECT * FROM tb_direcciones WHERE user = '".intval($_GET['myid'])."' ";
考虑在Web服务中添加一些安全性(身份验证)(PHP代码)。它似乎会传递太多的个人信息,如果它在一个普通的网络上工作,任何人都可以轻松接收您存储的数据。
答案 1 :(得分:1)
您可以使用post方法
@Override
protected String doInBackground(Void... params) {
HashMap<String, String> postDataParams = new HashMap<String,String>();
postDataParams.put("MyId", someIdHere);
postDataParams.put("SomeOtherID", someOtherHere);
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Config.URL_GET_ALL,postDataParams);
Log.d("URL", "URL_GET_ALL_FILTERED: " + result );
return result;
}
在PHP部分中,您需要清理用户输入。如果它是一个整数,你可以使用
$given_id = intval($REQUEST["MyId"]);
如Todor所述。如果是字符串,则需要使用预准备语句来避免SQL注入