A brief example of Android+php+mysql development

Source: Internet
Author: User
Tags deprecated php server

Android+php+mysql developing a simple example

Some time ago to do an Android project, need to use the database, before have written a little web related things, so plan to use mysql+php this gold partner, although a bit overqualified.

I am a genuine rookie, on Android do not understand, this project is purely gig, the reason why this blog is to write my project in the various problems encountered in the solution to share to everyone, I hope to help you.

Next I will explain how the Android client interacts with the MySQL database via PHP in three ways .

General statement

Simply put, the Android client sends a request to the local server via HTTP, accesses the specified PHP code, and the server executes the database operation via PHP code.
Returns the corresponding JSON data. The server can be understood as a computer running some server containers, such as your computer installed Apache and keep running, then the computer becomes a server, but this server is not in the network, only local access. The Android client submits a post or GET request through HttpURLConnection to the PHP file specified in the server, and the server-side PHP code accepts the parameters from the client (if it is a parameter pass) to perform the database operation, returning the JSON data to the client.
Below I use the Android client through the user name password login As an example to explain. Specifically, the client submits 2 parameters to the server via the Post method: User name (username) and password (password) to the specified login.php file (this file writes the PHP code of the login verification), The file returns the appropriate JSON data for the client by querying the database for the presence of the user and the correct password.
Now that Php+mysql is selected, it is convenient to use the Wamp server suite, and friends who have used it should pro.

1. Android Client

The work done by the Android client is to submit a post or GET request through HttpURLConnection to the login.php file specified in the server, and the server side accepts parameters from the client to perform the login.php file for the database operation, returning the JSON data to the client.
Here only the Code section, as for the interface only need 2 text edit box EditText used to enter the user name password, a button login buttons, its ID set itself.
The Login button response function is as follows
        Loginbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View                V) {//Login button to listen for Event/* ((APP) Getapplicationcontext ()). Settextdata (Et.gettext (). toString ());                    Location_x.settext ((APP) Getapplicationcontext ()). Gettextdata ()); */New Thread (new Runnable () { @Override public void Run () {try {int resul                            t = login (); Login () is the function that submits the request to the PHP server, the return data type is int if (result = = 1) {log.e ("Lo G_tag "," Landing success!                                ");                                Toast Toast=null;                                Looper.prepare (); Toast.maketext (Phpactivity.this, "Landing success!                                ", Toast.length_short). Show ();                            Looper.loop (); } else if (result = =-2) {LOG.E ("Log_tag", "Password wrong!"                                ");                                Toast Toast=null;                                Looper.prepare (); Toast.maketext (phpactivity.this, "wrong password!                                ", Toast.length_short). Show ();                            Looper.loop (); } else if (result = =-1) {LOG.E ("Log_tag", "the user does not exist!")                                ");                                Toast Toast=null;                                Looper.prepare (); Toast.maketext (Phpactivity.this, "the user does not exist!                                ", Toast.length_short). Show ();                            Looper.loop ();                        }} catch (IOException e) {System.out.println (E.getmessage ());            }}). Start (); }        });
The Login button response function has a login () function, which is the function of submitting a request to the server and getting the server to return the JSON data.
    /* * User Login Submit POST request * Submit data to Server 1.user_id username, 2.input_pwd password * Return JSON data {"Status": "1", "info": "Login Success", "Sex": "0        "," Nicename ":" "} */private int login () throws IOException {int returnresult=0;        /* Get user name and password */String user_id=et.gettext (). toString ();        String Input_pwd=pwd.gettext (). toString (); if (user_id==null| |            User_id.length () <=0) {looper.prepare ();            Toast.maketext (Phpactivity.this, "Please enter account", Toast.length_long). Show ();            Looper.loop ();        return 0; } if (input_pwd==null| |            Input_pwd.length () <=0) {looper.prepare ();            Toast.maketext (Phpactivity.this, "Please enter password", Toast.length_long). Show ();            Looper.loop ();        return 0;        } String urlstr= "http://192.168.191.1/LBS/login.php";        Establish the network connection URL url = new URL (urlstr);        HttpURLConnection http= (httpurlconnection) url.openconnection ();       Write post data to Web page, similar to Web page post method, with ' & ' connection between parameters String params= "uid=" +user_id+ ' & ' + "pwd=" +INPUT_PWD;        Http.setdooutput (TRUE);        Http.setrequestmethod ("POST");        OutputStream Out=http.getoutputstream ();        Out.write (Params.getbytes ());//post Submit parameter Out.flush ();        Out.close ();         Read the data returned by the webpage BufferedReader bufferedreader=new BufferedReader (New InputStreamReader (Http.getinputstream ()));//Get input stream        String line= "";            StringBuilder sb=new StringBuilder ()//Create input buffer while (null!= (Line=bufferedreader.readline ())) {//end reads a null value             Sb.append (line);//write Buffer} String result= sb.tostring ();//Returns the result try {/* Gets the JSON data returned by the server */            Jsonobject jsonobject= New Jsonobject (result); Returnresult=jsonobject.getint ("status");//Get the Status field value in JSON data} catch (Exception e) {//Todo:handle EX        Ception log.e ("Log_tag", "The Error parsing Data" +e.tostring ());    } return Returnresult; }
Here are a few notes for this login () function:
1) urlstr= "http://192.168.191.1/LBS/login.php". Where 192.168.191.1 is the address of the Apache server running on the local computer, this address is mapped to the WWW directory under the Wamp installation directory, and lbs is the folder under the WWW directory.
At first I used Android studio to bring the simulator to test, the internet said that the browser access to 10.0.2.0 or something can access the local Apache server on the computer, but did not successfully access the WAMP's own Apache server.
Finally find an excellent method, is to use the real machine test, as the server computer needs to install a WiFi sharing software (such as Cheetah WiFi), with the real machine to be tested connected to the WiFi, mobile browser access to http://192.168.191.1, if the display
If the mobile phone access to the computer Apache server success, this server environment has been built successfully. Login.php is placed under the Apache server of the computer, for example, my is under the D:\wamp\www\LBS folder.
2) HttpURLConnection. I have been on the internet to find some of the methods of the Android network request, but most of them have been deprecated, the use of httpurlconnection is not currently deprecated a method, of course, for the master, this is not worth mentioning.
3) Jsonobject.
Since the data returned in the following PHP code is of the JSON data type, it is not difficult to do so in the client, so it is not clear that you can search for it.
4) has said before, I do not know about Android, so in the test made a big taboo, that is, network access can not be placed in the main thread, or will block the main thread, causing the UI suspended animation and other errors, so need to open a single thread, that
The Run method in the Login button response function.

2. Server-side

login.php in the server container, responding to external access requests at all times, the main tasks are:
1) Get the user name password sent by the mobile phone via POST request.
2) Connect to the database to find out if there are records consistent with the user name password, and return different JSON data based on the lookup results.
3) JSON data is an effective way to interact with the server side of the client.
<?php  /** User Login, server processing */include ("conn.php");    mysql_select_db ("lbs");  $getid =$_post[' UID '];//client post the user name $getpwd=$_post[' pwd '];//the client post the password    $sql =mysql_query ("SELECT * from user WHERE userid = ' $getid ' "); $result =mysql_fetch_assoc ($sql), if (!empty ($result)) {//exists the user if ($getpwd = = $result [' password ']) {//user name password matches correctly mysql_ Query ("UPDATE user SET status= ' 1 ' WHERE id = $result [id]");/* The array here does not need to add single quotes */$back [' Status ']= ' 1 '; $back [' Info ']= "Login Success "; $back [' Sex ']= $result [' sex ']; $back [' Nicename ']= $result [' Nicename '];echo (Json_encode ($back)); }else{/* Password Error */$back [' Status ']= '-2 '; $back [' Info ']= ' password error '; Echo (Json_encode ($back));}} else{//does not exist for the user $back[' status ']= ' 1 '; $back [' Info ']= ' user not exist '; Echo (Json_encode ($back));}             Mysql_close ();  ? >

Where conn.php is the database connection file, the code is as follows

<?phperror_reporting (E_all & ~e_notice & ~e_deprecated);     $conn =mysql_connect ("localhost", "root", "admin") or Die ("Database Server connection Error". Mysql_error ());     mysql_select_db ("Mylocation", $conn) or Die ("Database access Error". Mysql_error ());      mysql_query ("SET NAMES ' UTF8 '");? >

3.MYSQL Database

As for the database, can be built on its own, according to the above PHP code, the database has a user table, the table has 4 fields, respectively, is userid,password,nicename,sex. You can build it yourself (Nicename,sex is not used in this example). As follows

After the above work is complete, deploy the client to a real machine for testing

Enter the user name password, click the login button, the results are as follows:

4. Summary:

What this article says is only PHP and the simplest example of Android, in fact, there are many major projects are using this model, such as Sina Weibo client, interested readers can query the relevant data such as " android+php Best Practices , again, because I am also a rookie, from many predecessors of the blog learned a lot, so here and everyone to share their learning experience, so if there are errors in the article also welcome everyone to criticize.

Key source

PS:CSDN when to make your own text editing tools to do a little better.

This article explains the Android+php+mysql development simple example, more relevant content please pay attention to the PHP Chinese network.

Related recommendations:

A detailed explanation of $this usage in PHP

The association between Java and PHP

Summary of practical PHP experience

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.