如何从Android传递变量,让PHP文件读取,然后读取MYSQL数据库并返回其他数据


How to pass variables from Android to be read by a PHP file, which then reads MYSQL Database and returns other data?

这是我的PHP文件,需要从android接收asort变量,然后使用它可以从数据库中提取特定数据:

php
    include('connect.php');
    $asortid=$_POST['asortid'];
    $asortlastname=$_POST['asortlastname'];
    $asortemail=$_POST['asortemail'];
    $afilter = $_POST['afilter'];
    if ($afilter=='') { $asorturgency="5"}
    if ($afilter!='') {
    // SET FILTERS
    if ($asortid=='' || $asortid=='All ID') { $mysortid="%"; } else{
 $mysortid="%".$asortid."%"; 
}
        if ($asortemail=='' || $asortemail=='Any Email') { 
$mysortemail="%"; } else { 
$mysortemail="%".$asortemail."%"; }

    // MASTER RESULT QUERY
    $query=mysql_query("SELECT * FROM names WHERE (id LIKE '".$mysortid."') AND (email        LIKE '".$mysortemail."');
    //execute query
    try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
    }
   // Finally, we can retrieve all of the found rows into an array using fetchAll 
   $rows = $stmt->fetchAll();
   if ($rows) {
    $response["success"] = 1;
    $response["message"] = "Post Available!";
    $response["posts"]   = array();

        foreach ($rows as $row) {
            $post             = array();
            $post["id"] = $row["id"];
            $post["firstname"]  = $row["firstname"];
                    $post["middlename"] = $row["middlename"];
            $post["lastname"]  = $row["lastname"];
                    $post["email"] = $row["email"];
            $post["comments"]  = $row["comments"];
        //update our repsonse JSON data
       array_push($response["posts"], $post);
     }
      //echoing JSON response
     echo json_encode($response);
    } 
     else {
    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));
    }

这是我的android文件,我试图发送要读取的帖子数据:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Display extends ListActivity {
    // Progress Dialog
    private ProgressDialog tDialog;
    JSONParser myjsonParser = new JSONParser();
    private static final String SORTNAMES = "http://leadpronow.com/demo/sortnames.php";
    String sortid, sortname, sorturgency, filtered;
    // JSON IDS:
    private static final String TAG_DPOSTS = "posts";
    private static final String TAG_DID = "id";
    private static final String TAG_DFIRSTNAME = "firstname";
    private static final String TAG_DMIDDLENAME = "middlename";
    private static final String TAG_DLASTNAME = "lastname";
    private static final String TAG_DEMAIL = " email";
    private static final String TAG_DCOMMENTS = "comments";
    // An array of all of our leads
    private JSONArray mName = null;
    // manages all of our comments in a list.
    private ArrayList<HashMap<String, String>> mNameList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // note that use read_comments.xml instead of our single_post.xml
        setContentView(R.layout.readpost);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // loading the comments via AsyncTask
        new LoadNames().execute();
    }
    public void updateJSONdata() {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(SORTNAMES);
        try {
            Intent in = getIntent();
            filtered = in.getStringExtra("filtered");
            sortid = in.getStringExtra("sortid");
            sortemail = in.getStringExtra("sortemail");
            sorturgency = in.getStringExtra("sorturgency");

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>    (4);
            nameValuePairs.add(new BasicNameValuePair("afilter", filtered));
            nameValuePairs.add(new BasicNameValuePair("asortid", sortid));
            nameValuePairs.add(new BasicNameValuePair("asortemail",sortemail));
            nameValuePairs.add(new  BasicNameValuePair("asorturgency",sorturgency));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpresponse = httpclient.execute(httppost);
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        mNamesList = new ArrayList<HashMap<String, String>>();
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(SORTNAMES);
        try {
            mLeads = json.getJSONArray(TAG_DPOSTS);
            // looping through all posts according to the json object returned
            for (int i = 0; i < mLeads.length(); i++) {
                JSONObject c = mLeads.getJSONObject(i);
                // gets the content of each tag
                String did = c.getString(TAG_DID);
                String dfirstname = c.getString(TAG_DFIRSTNAME);
                String dmiddlename = c.getString(TAG_DMIDDLENAME);
                String dlastname = c.getString(TAG_DLASTNAME);
                String demail = c.getString(TAG_DEMAIL);
                String dcomments = c.getString(TAG_DCOMMENTS);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_DID, did);
                map.put(TAG_DFIRSTNAME, dfirstname);
                map.put(TAG_DMIDDLENAME, dmiddlename);
                map.put(TAG_DLASTNAME, dlastname);
                map.put(TAG_DEMAIL, demail);
                            map.put(TAG_DCOMMENTS, dcomments);
                // adding HashList to ArrayList
                mLeadsList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /**
     * Inserts the parsed data into the listview.
     */
    private void updateList() {
        // For a ListActivity we need to set the List Adapter, and in order to
        // do
        // that, we need to create a ListAdapter. This SimpleAdapter,
        // will utilize our updated Hashmapped ArrayList,
        // use our single_post xml template for each item in our list,
        // and place the appropriate info from the list to the
        // correct GUI id. Order is important here.
        ListAdapter adapter = new SimpleAdapter(this, mNamesList,
                R.layout.singlelead, new String[] { TAG_DFIRSTNAME,
                        TAG_DMIDDLENAME, TAG_DLASTNAME, TAG_DID,
                        TAG_DEMAIL, TAG_DCOMMENTS},
                new int[] { R.id.dlfirstname, R.id.dlmiddlename,
                        R.id.dllastname, R.id.dlid, R.id.dlemail,
                        R.id.dlcomments});
        setListAdapter(adapter);
        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                // getting values from selected ListItem
                String longid = ((TextView) v.findViewById(R.id.id)).getText()
                        .toString();
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), EditUsers.class);
                // sending pid to next activity
                in.putExtra("Listitem", longid);
                // starting new activity and expecting some response back
                startActivity(in);
            }
        });
    }
    public class LoadLeads extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tDialog = new ProgressDialog(LeadDisplay.this);
            tDialog.setMessage("Loading Leads...");
            tDialog.setIndeterminate(false);
            tDialog.setCancelable(true);
            tDialog.show();
        }
        @Override
        protected Boolean doInBackground(Void... arg0) {
            updateJSONdata();
            return null;
        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            tDialog.dismiss();
            updateList();
        }
    }
}

所以我需要id,firstname,middlename,lastname,电子邮件和评论来显示在我的列表视图中。我的错误是没有可用的帖子。

07-31 09:58:43.943: E/JSON Parser(13176): Error parsing data org.json.JSONException: End of input at character 0 of 
07-31 09:58:43.943: W/System.err(13176): org.json.JSONException: No value for posts
07-31 09:58:43.943: W/System.err(13176):    at org.json.JSONObject.get(JSONObject.java:354)
07-31 09:58:43.943: W/System.err(13176):    at org.json.JSONObject.getJSONArray(JSONObject.java:544)
07-31 09:58:43.943: W/System.err(13176):    at com.example.mysqltest.LeadDisplay.updateJSONdata(LeadDisplay.java:151)
07-31 09:58:43.943: W/System.err(13176):    at com.example.mysqltest.LeadDisplay$LoadLeads.doInBackground(LeadDisplay.java:252)
07-31 09:58:43.943: W/System.err(13176):    at com.example.mysqltest.LeadDisplay$LoadLeads.doInBackground(LeadDisplay.java:1)
07-31 09:58:43.943: W/System.err(13176):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-31 09:58:43.943: W/System.err(13176):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-31 09:58:43.943: W/System.err(13176):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-31 09:58:43.943: W/System.err(13176):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-31 09:58:43.943: W/System.err(13176):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-31 09:58:43.943: W/System.err(13176):    at java.lang.Thread.run(Thread.java:856)
07-31 09:58:43.963: I/endeffect(13176): AbsListView.onMeasure(), getWidth()=1080,

使用链接

String link = "http://localhost/login.php?username="
        +username+"&password="+password;

在php中编写insert或任何查询,然后通过在链接中传递变量将数据发送到php。还(提示)使用AsyncTask 从android发送数据