【问题标题】:How to retrieve a selected row's form MySQL database and send back the information to Android?如何从 MySQL 数据库中检索选定的行并将信息发送回 Android?
【发布时间】:2023-04-02 10:28:02
【问题描述】:

我正在开发一个 Android 项目,我对 Android 完全陌生。我正在关注以下教程link。我的项目是关于警察登记系统的。我在 PHP 和 JSON 的帮助下连接到 MySQL 数据库。

我创建了一个用户可以注册的表单,他们可以使用他们的用户名和密码登录。我还制作了一个表格,用户可以在其中注册他们的投诉,投诉存储在数据库中称为db_complaints 的单个数据库中。我可以使用以下 PHP 代码检索所有投诉。

<?php

/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script.  Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.inc.php");

//initial query

if (!empty($_POST)) {
	//initial query
	$query = "INSERT INTO complaints ( username, title, message ) VALUES ( :user, :title, :message ) ";

    //Update query
    $query_params = array(
        ':user' => $_POST['username'],
        ':title' => $_POST['title'],
		':message' => $_POST['message']
    );


  
//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["post_id"]  = $row["post_id"];

        $post["username"] = $row["username"];
        $post["title"]    = $row["title"];
        $post["message"]  = $row["message"];
        
        
        //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));
}}

?>

我想单独检索特定用户的投诉,以便他们可以在 my_complaints 表单中查看投诉,但我无法做到这一点,我被卡住了。

【问题讨论】:

  • 该代码用于保存投诉。你写过代码来阅读投诉吗?

标签: php android mysql json


【解决方案1】:

使用准备好的语句和错误处理,您的代码看起来非常整洁,那么您的问题到底出在哪里?

$query = "SELECT * FROM complaints WHERE username = :user";
$query_params = array(':user' => $_POST['username']);

该查询应该可以检索特定用户的投诉。

【讨论】:

  • 我使用了代码,但 php 脚本说“没有 postavailable”:(
  • 非常感谢,我在我的 php 表单中使用了你的 php 代码,并稍微修改了我的 android 代码,现在我可以在登录时轻松解决特定用户的投诉,谢谢: )
  • 好的,很好!您可以投票并接受答案吗? :D
【解决方案2】:

这是我在 android 中用来检索所有用户投诉的代码

package com.example.policadda;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

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.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Mycomplaints extends ListActivity {

	// Progress Dialog
	private ProgressDialog pDialog;
 
	//php read comments script
    
    //localhost :  
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String READ_COMMENTS_URL = "http://xxx.xxx.x.x:1234/webservice/comments.php";
    
    //testing on Emulator:
    private static final String READ_COMMENTS_URL = "http://www.iamnotcrazy.hol.es/webservice/mycomplaints.php";
    
  //testing from a real server:
    //private static final String READ_COMMENTS_URL = "http://www.mybringback.com/webservice/comments.php";
   
  //JSON IDS:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_TITLE = "title";
    private static final String TAG_POSTS = "posts";
    private static final String TAG_COMPLAINT_ID = "complaint_id";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_SUBJECT = "subject";
    //it's important to note that the message is both in the parent branch of 
    //our JSON tree that displays a "Post Available" or a "No Post Available" message,
    //and there is also a message for each individual post, listed under the "posts"
    //category, that displays what the user typed as their message.
    

   //An array of all of our comments
    private JSONArray mComments = null;
    //manages all of our comments in a list.
    private ArrayList<HashMap<String, String>> mCommentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //note that use read_comments.xml instead of our single_post.xml
        setContentView(R.layout.my_complaints);   
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	//loading the comments via AsyncTask
    	new LoadComments().execute();
    }

	public void addComment(View v)
    {
        Intent i = new Intent(Mycomplaints.this, Complaints.class);
        startActivity(i);
    }

    /**
     * Retrieves json data of comments
     */
	public void updateJSONdata() {

        // Instantiate the arraylist to contain all the JSON data.
    	// we are going to use a bunch of key-value pairs, referring
    	// to the json element name, and the content, for example,
    	// message it the tag, and "I'm awesome" as the content..
    	
        mCommentList = new ArrayList<HashMap<String, String>>();
        
        // Bro, it's time to power up the J parser 
        JSONParser jParser = new JSONParser();
        // Feed the beast our comments url, and it spits us
        //back a JSON object.  Boo-yeah Jerome.
        JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

        //when parsing JSON stuff, we should probably
        //try to catch any exceptions:
        try {
            
        	//I know I said we would check if "Posts were Avail." (success==1)
        	//before we tried to read the individual posts, but I lied...
        	//mComments will tell us how many "posts" or comments are
        	//available
            mComments = json.getJSONArray(TAG_POSTS);

            // looping through all posts according to the json object returned
            for (int i = 0; i < mComments.length(); i++) {
                JSONObject c = mComments.getJSONObject(i);

                //gets the content of each tag
                String title = c.getString(TAG_TITLE);
                String content = c.getString(TAG_SUBJECT);
                String username = c.getString(TAG_USERNAME);
                

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
              
                map.put(TAG_TITLE, title);
                map.put(TAG_SUBJECT, content);
                map.put(TAG_USERNAME, username);
             
                // adding HashList to ArrayList
                mCommentList.add(map);
                
                //annndddd, our JSON data is up to date same with our array list
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * Inserts the parsed data into our 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, mCommentList,
				R.layout.single_post, new String[] { TAG_TITLE, TAG_SUBJECT,
						TAG_USERNAME }, new int[] { R.id.title, R.id.message,
						R.id.username });

		// I shouldn't have to comment on this one:
		setListAdapter(adapter);
		
		// Optional: when the user clicks a list item we 
		//could do something.  However, we will choose
		//to do nothing...
		ListView lv = getListView();	
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// This method is triggered if an item is click within our
				// list. For our example we won't be using this, but
				// it is useful to know in real life applications.

			}
		});
	}       

    public class LoadComments extends AsyncTask<Void, Void, Boolean> {

    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Mycomplaints.this);
			pDialog.setMessage("Loading complaints...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}
        @Override
        protected Boolean doInBackground(Void... arg0) {
        	//we will develop this method in version 2
        	  updateJSONdata();

            return null;

        }


        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
          //we will develop this method in version 2
            updateList();
        }
    }
}

【讨论】:

    【解决方案3】:

    这是我根据您在 php 中的建议更改的代码

    <?php
    
    /*
    Our "config.inc.php" file connects to database every time we include or require
    it within a php script.  Since we want this script to add a new user to our db,
    we will be talking with our database, and therefore,
    let's require the connection to happen:
    */
    require("config.inc.php");
    //initial query
    $query = "Select * FROM complaint WHERE username= :user";
    $query_params = array(':user' => $_POST['username']);
    //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["complaint_id"]  = $row["complaint_id"];
            $post["username"] = $row["username"];
            $post["title"]    = $row["title"];
            $post["subject"]  = $row["subject"];
            
            
            //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,使我使用共享首选项来存储用户名并将其发送到 php,而 php 可以接收用户名并执行代码:)。下面是我的安卓代码。

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Locale;
    
    import org.apache.http.NameValuePair;
    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.content.SharedPreferences;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    
    public class Mycomplaints extends ListActivity {
    
    	// Progress Dialog
    	private ProgressDialog pDialog;
        JSONParser jsonParser = new JSONParser();
    	//php read comments script
        
        //localhost :  
        //testing on your device
        //put your local ip instead,  on windows, run CMD > ipconfig
        //or in mac's terminal type ifconfig and look for the ip under en0 or en1
       // private static final String READ_COMMENTS_URL = "http://xxx.xxx.x.x:1234/webservice/comments.php";
        
        //testing on Emulator:
        private static final String READ_COMPLAINTS_URL = "http://www.iamnotcrazy.hol.es/webservice/mycomplaints.php";
        
      //testing from a real server:
        //private static final String READ_COMMENTS_URL = "http://www.mybringback.com/webservice/comments.php";
       
      //JSON IDS:
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_TITLE = "title";
        private static final String TAG_POSTS = "posts";
        private static final String TAG_COMPLAINT_ID = "complaint_id";
        private static final String TAG_USERNAME = "username";
        private static final String TAG_SUBJECT = "subject";
        //it's important to note that the message is both in the parent branch of 
        //our JSON tree that displays a "Post Available" or a "No Post Available" message,
        //and there is also a message for each individual post, listed under the "posts"
        //category, that displays what the user typed as their message.
        
    
       //An array of all of our comments
        private JSONArray mComments = null;
        //manages all of our comments in a list.
        private ArrayList<HashMap<String, String>> mCommentList;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //note that use read_comments.xml instead of our single_post.xml
            setContentView(R.layout.my_complaints);   
        }
        
        @Override
        protected void onResume() {
        	// TODO Auto-generated method stub
        	super.onResume();
        	//loading the comments via AsyncTask
        	new LoadComments().execute();
        }
    
    	public void addComment(View v)
        {
            Intent i = new Intent(Mycomplaints.this, Complaints.class);
            startActivity(i);
        }
    
        /**
         * Retrieves json data of comments
         */
    	public void updateJSONdata() {
    
            // Instantiate the arraylist to contain all the JSON data.
        	// we are going to use a bunch of key-value pairs, referring
        	// to the json element name, and the content, for example,
        	// message it the tag, and "I'm awesome" as the content..
        	
            mCommentList = new ArrayList<HashMap<String, String>>();
            
            // Bro, it's time to power up the J parser 
            JSONParser jParser = new JSONParser();
            // Feed the beast our comments url, and it spits us
            //back a JSON object.  Boo-yeah Jerome.
            JSONObject json = jParser.getJSONFromUrl(READ_COMPLAINTS_URL);
            
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Mycomplaints.this);
                String post_username = sp.getString("username", "diva");
            //when parsing JSON stuff, we should probably
            //try to catch any exceptions:
            try {
                  List<NameValuePair> params = new ArrayList<NameValuePair>();
    			   params.add(new BasicNameValuePair("username", post_username));
                   Log.d("request!", "starting");
    
    			     JSONObject json1 = jsonParser.makeHttpRequest(
    			    		 READ_COMPLAINTS_URL, "POST", params);
            	//I know I said we would check if "Posts were Avail." (success==1)
            	//before we tried to read the individual posts, but I lied...
            	//mComments will tell us how many "posts" or comments are
            	//available
                mComments = json1.getJSONArray(TAG_POSTS);
    
                // looping through all posts according to the json object returned
                for (int i = 0; i < mComments.length(); i++) {
                    JSONObject c = mComments.getJSONObject(i);
    
                    //gets the content of each tag
                    String title = c.getString(TAG_TITLE);
                    String content = c.getString(TAG_SUBJECT);
                    String username = c.getString(TAG_USERNAME);
                    
    
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                  
                    map.put(TAG_TITLE, title);
                    map.put(TAG_SUBJECT, content);
                    map.put(TAG_USERNAME, username);
                 
                    // adding HashList to ArrayList
                    mCommentList.add(map);
                    
                    //annndddd, our JSON data is up to date same with our array list
                }
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Inserts the parsed data into our 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, mCommentList,
    				R.layout.single_post, new String[] { TAG_TITLE, TAG_SUBJECT,
    						TAG_USERNAME }, new int[] { R.id.title, R.id.message,
    						R.id.username });
    
    		// I shouldn't have to comment on this one:
    		setListAdapter(adapter);
    		
    		// Optional: when the user clicks a list item we 
    		//could do something.  However, we will choose
    		//to do nothing...
    		ListView lv = getListView();	
    		lv.setOnItemClickListener(new OnItemClickListener() {
    
    			@Override
    			public void onItemClick(AdapterView<?> parent, View view,
    					int position, long id) {
    
    				// This method is triggered if an item is click within our
    				// list. For our example we won't be using this, but
    				// it is useful to know in real life applications.
    
    			}
    		});
    	}       
    
        public class LoadComments extends AsyncTask<Void, Void, Boolean> {
    
        	@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    			pDialog = new ProgressDialog(Mycomplaints.this);
    			pDialog.setMessage("Loading complaints...");
    			pDialog.setIndeterminate(false);
    			pDialog.setCancelable(true);
    			pDialog.show();
    		}
            @Override
            protected Boolean doInBackground(Void... arg0) {
            	//we will develop this method in version 2
            	  updateJSONdata();
    
                return null;
    
            }
    
    
            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                pDialog.dismiss();
              //we will develop this method in version 2
                updateList();
            }
        }
    }

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 2020-07-10
      • 1970-01-01
      • 2023-03-11
      • 2012-02-09
      • 2021-06-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多