Android 简明教程

Android - PHP/MYSQL

在本章中,我们将解释如何将 PHP 和 MYSQL 与您的 Android 应用程序集成在一起。如果您有一个网络服务器,并且您希望在您的 Android 应用程序上访问其数据,这是非常有用的。

In this chapter , we are going to explain, how you can integrate PHP and MYSQL with your android application. This is very useful in case you have a webserver, and you want to access its data on your android application.

MYSQL 作为网络服务器上的数据库使用,PHP 用于从数据库中获取数据。我们的应用程序将与 PHP 页面进行必要的参数通信,PHP 将联系 MYSQL 数据库,获取结果并向我们返回结果。

MYSQL is used as a database at the webserver and PHP is used to fetch data from the database. Our application will communicate with the PHP page with necessary parameters and PHP will contact MYSQL database and will fetch the result and return the results to us.

PHP - MYSQL

Creating Database

使用此简单脚本来轻松创建 MYSQL 数据库。 CREATE DATABASE 语句创建数据库。

MYSQL database can be created easily using this simple script. The CREATE DATABASE statement creates the database.

<?php
   $con=mysqli_connect("example.com","username","password");
   $sql="CREATE DATABASE my_db";
   if (mysqli_query($con,$sql)) {
      echo "Database my_db created successfully";
   }
?>

Creating Tables

一旦创建了数据库,就是时候在数据库中创建一些表了。 CREATE TABLE 语句创建数据库。

Once database is created, its time to create some tables in the database. The CREATE TABLE statement creates the database.

<?php
   $con=mysqli_connect("example.com","username","password","my_db");
   $sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))";
   if (mysqli_query($con,$sql)) {
      echo "Table have been created successfully";
   }
?>

Inserting Values in tables

当数据库和表创建好后,现在是时候将一些数据插入表中了。 Insert Into 语句创建数据库。

When the database and tables are created. Now its time to insert some data into the tables. The Insert Into statement creates the database.

<?php
   $con=mysqli_connect("example.com","username","password","my_db");
   $sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin', 'admin','adminstrator')";
   if (mysqli_query($con,$sql)) {
      echo "Values have been inserted successfully";
   }
?>

PHP - GET and POST methods

PHP 还用于在创建后从 mysql 数据库中获取记录。为了获取记录,必须将一些信息传递给 PHP 页面,说明要获取什么记录。

PHP is also used to fetch the record from the mysql database once it is created. In order to fetch record some information must be passed to PHP page regarding what record to be fetched.

传递信息的第一种方法是通过 GET 方法,其中使用了 $_GET 命令。变量在 url 中传递,并且提取记录。它的语法如下所示:

The first method to pass information is through GET method in which $_GET command is used. The variables are passed in the url and the record is fetched. Its syntax is given below −

<?php
   $con=mysqli_connect("example.com","username","password","database name");

   if (mysqli_connect_errno($con)) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }

   $username = $_GET['username'];
   $password = $_GET['password'];
   $result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username'
      and Password='$password'");
   $row = mysqli_fetch_array($result);
   $data = $row[0];

   if($data){
      echo $data;
   }
   mysqli_close($con);
?>

第二种方法是使用 POST 方法。上述脚本的唯一更改是用 $_POST 替换 $_GET。在 Post 方法中,变量不会通过 URL 传递。

The second method is to use POST method. The only change in the above script is to replace $_GET with $_POST. In Post method, the variables are not passed through URL.

Android - Connecting MYSQL

Connecting Via Get Method

有两种方法可以通过 PHP 页面连接到 MYSQL。第一个称为 Get method 。我们将使用 HttpGetHttpClient 类连接。它们的语法如下所示:

There are two ways to connect to MYSQL via PHP page. The first one is called Get method. We will use HttpGet and HttpClient class to connect. Their syntax is given below −

URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));

之后,您需要调用 HttpClient 类的 execute 方法并在 HttpResponse 对象中接收它。之后,您需要打开流以接收数据。

After that you need to call execute method of HttpClient class and receive it in a HttpResponse object. After that you need to open streams to receive the data.

HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));

Connecting Via Post Method

在 Post 方法中,将使用 URLEncoderURLConnection 类。urlencoder 将对传入变量的信息进行编码。其语法如下所示:

In the Post method, the URLEncoder,URLConnection class will be used. The urlencoder will encode the information of the passing variables. It’s syntax is given below −

URL url = new URL(link);
String data  = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URLConnection conn = url.openConnection();

您需要做的最后一件事是将此数据写入链接。写入后,您需要打开流以接收已响应的数据。

The last thing you need to do is to write this data to the link. After writing, you need to open stream to receive the responded data.

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));

Example

以下示例是通过 PHP 页面将 Android 应用程序与 MYSQL 数据库连接的完整示例。它创建了一个基本应用程序,允许您使用 GET 和 POST 方法登录。

The below example is a complete example of connecting your android application with MYSQL database via PHP page. It creates a basic application that allows you to login using GET and POST method.

PHP - MYSQL part

在此示例中,已在 000webhost.com 上创建了一个名为 temp 的数据库。在该数据库中,已创建一个名为 table1 的表。此表有三个字段。(用户名,密码,角色)。该表只有一条记录,即 (“admin”、“admin”、“administrator”)。

In this example a database with the name of temp has been created at 000webhost.com. In that database, a table has been created with the name of table1. This table has three fields. (Username, Password, Role). The table has only one record which is ("admin","admin","administrator").

下面给出了通过 post 方法获取参数的 php 页面。

The php page has been given below which takes parameters by post method.

<?php
   $con=mysqli_connect("mysql10.000webhost.com","username","password","db_name");

   if (mysqli_connect_errno($con)) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }

   $username = $_POST['username'];
   $password = $_POST['password'];
   $result = mysqli_query($con,"SELECT Role FROM table1 where
   Username='$username' and Password='$password'");
   $row = mysqli_fetch_array($result);
   $data = $row[0];

   if($data){
      echo $data;
   }

   mysqli_close($con);
?>

Android Part

要测试此示例,您需要在已连接 wifi 互联网的实际设备上运行它。

To experiment with this example , you need to run this on an actual device on which wifi internet is connected.

Steps

Description

1

You will use Android studio IDE to create an Android application and name it as PHPMYSQL under a package com.example.phpmysql.

2

Modify src/MainActivity.java file to add Activity code.

3

Create src/SiginActivity.java file to add PHPMYSQL code.

4

Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

5

Modify res/values/string.xml file and add necessary string components.

6

Modify AndroidManifest.xml to add necessary permissions.

7

Run the application and choose a running android device and install the application on it and verify the results.

以下是 src/com.example.phpmysql/MainActivity.java 的内容。

Here is the content of src/com.example.phpmysql/MainActivity.java.

package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

   private EditText usernameField,passwordField;
   private TextView status,role,method;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      usernameField = (EditText)findViewById(R.id.editText1);
      passwordField = (EditText)findViewById(R.id.editText2);

      status = (TextView)findViewById(R.id.textView6);
      role = (TextView)findViewById(R.id.textView7);
      method = (TextView)findViewById(R.id.textView9);
   }



   public void login(View view){
      String username = usernameField.getText().toString();
      String password = passwordField.getText().toString();
      method.setText("Get Method");
      new SigninActivity(this,status,role,0).execute(username,password);

   }

   public void loginPost(View view){
      String username = usernameField.getText().toString();
      String password = passwordField.getText().toString();
      method.setText("Post Method");
      new SigninActivity(this,status,role,1).execute(username,password);
   }
}

以下是 src/com.example.phpmysql/SigninActivity.java 的内容。

Here is the content of src/com.example.phpmysql/SigninActivity.java.

package com.example.phpmysql;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity  extends AsyncTask{
   private TextView statusField,roleField;
   private Context context;
   private int byGetOrPost = 0;

   //flag 0 means get and 1 means post.(By default it is get.)
   public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) {
      this.context = context;
      this.statusField = statusField;
      this.roleField = roleField;
      byGetOrPost = flag;
   }

   protected void onPreExecute(){
   }

   @Override
   protected String doInBackground(String... arg0) {
      if(byGetOrPost == 0){ //means by Get Method

         try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];
            String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;

            URL url = new URL(link);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            BufferedReader in = new BufferedReader(new
               InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while ((line = in.readLine()) != null) {
               sb.append(line);
               break;
            }

            in.close();
            return sb.toString();
         } catch(Exception e){
            return new String("Exception: " + e.getMessage());
         }
      } else{
         try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];

            String link="http://myphpmysqlweb.hostei.com/loginpost.php";
            String data  = URLEncoder.encode("username", "UTF-8") + "=" +
               URLEncoder.encode(username, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
               URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();

            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write( data );
            wr.flush();

            BufferedReader reader = new BufferedReader(new
               InputStreamReader(conn.getInputStream()));

            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null) {
               sb.append(line);
               break;
            }

            return sb.toString();
         } catch(Exception e){
            return new String("Exception: " + e.getMessage());
         }
      }
   }

   @Override
   protected void onPostExecute(String result){
      this.statusField.setText("Login Successful");
      this.roleField.setText(result);
   }
}