我想在同一个 session 中按此顺序实现以下目标:
- 获取android变量(imei)
- 发送变量到php
- 在sql中使用变量
- 将结果发送回android
我使用以下内容:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
// 01 - first i get imei
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
// 02 - then i call class to post imei to php
new loadData().execute();
// 03 - on php side i use "select ... where $imei ..."
// 04 - get the results back to android
// (yes i am aware that this method is commented out, i will explain why below)
//accessWebService();
}
发布:
class loadData extends AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String imeino = String.valueOf(IMEI);
nameValuePairs.add(new BasicNameValuePair("imeino",imeino));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://blah/contacts.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Error Send",e.toString());
}
return id;
}
}
获取
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("jsonResult: "+jsonResult);
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://blah/contacts.php" });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("contact_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("Name");
String number = jsonChildNode.optString("Number");
String username = jsonChildNode.optString("Username");
String status = jsonChildNode.optString("Status");
System.out.println("jsonResult: "+jsonResult);
System.out.println("getName: "+name);
System.out.println("getNumber: "+number);
System.out.println("getUsername: "+username);
System.out.println("getStatus: "+status);
}
} catch (JSONException e) {
System.out.println("Json Error" +e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
PHP:
<?php
include 'config.php';
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
//$imei = "000000000000000";
$sql = "select * from users WHERE IMEI ='$imei'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['contact_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
$f = fopen("log.txt", "w");
fwrite($f, print_r($json, true));
fclose($f);
?>
好的,下面是代码的故事:
当我只是 POST [ new loadData().execute()
] 而不是 GET [ accessWebService();
] 时,我可以读取我的 $imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
变量为 0000000000000
但当然我无法返回结果,因为 accessWebService()
被注释掉了。
然而,当我取消注释 accessWebService()
时,我可以将结果返回到 android 但它们是 null
因为现在 $imei = isset($_POST[' imeino'])? $_POST['imeino'] : '';
为空。
总结一下:
每当我调用 GET 方法时,我都会丢失我的 POST 变量!
最佳答案
PHP
要在 PHP 中同时支持 GET
和 POST
变量,您可以使用 $_REQUEST
:
$imei = isset($_REQUEST['imeino']) ? $_REQUEST['imeino'] : '';
检查参数是否已设置也是明智的做法,如果未设置则返回错误:
if ( empty($imei) ) {
echo json_encode( array( 'error' => 'Missing imeino parameter' ) );
return;
}
而且,非常重要的是,在将输入传递给 mysql 之前对其进行清理。这很危险:
$sql = "select * from users WHERE IMEI ='$imei'";
因为有人可能会使用 contacts.php?imeino=';DROP TABLE users' 调用您的 PHP 脚本
。 See here获取更多信息。
顺便说一下,PHP's mysql module is deprecated ;我建议使用 PDO .
Java
访问 API 的 GET
方法只需要一个小改动,将 imeino
参数传递给您的 PHP 脚本:
public void accessWebService( String imei ) {
JsonReadTask task = new JsonReadTask();
task.execute(new String[] { "http://blah/contacts.php?imeino=" + imei });
}
并且,您需要使用 IMEI 调用 accessWebService
。
关于php - Json 使用 WHERE column = $variable 读取 mysql 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33971566/