Home > Backend Development > PHP Tutorial > Android server development (1) Android combined with PHP to implement the database connection verification login function (with all codes attached)_PHP tutorial

Android server development (1) Android combined with PHP to implement the database connection verification login function (with all codes attached)_PHP tutorial

WBOY
Release: 2016-07-13 10:09:54
Original
1044 people have browsed it

Android server development (1) Android combined with PHP to implement database connection verification login function (with all codes attached)

No need to say anything, just go to the code. If you don’t understand, leave a message with me below.


Look at the server first: using PHP language, deployed on Sina sae server (with its own database)

Put all php files in the same directory:


1.db.php encapsulated class for connecting to the database


<?php
class Db{  
    static private $_instance;  
    static private $_connectSource;  
	//因为是连接新浪sae服务器所以下面的参数不生效。
    /*private $_dbConfig=array(  
        &#39;host&#39;=>&#39;127.0.0.1&#39;,  
        &#39;user&#39;=>&#39;root&#39;,  
        &#39;password&#39;=>&#39;&#39;,  
        &#39;database&#39;=>&#39;value&#39;  
    ); */ 
    private function _construct(){  
        
    }  
  
    static public function getInstance(){  
        //如果没有实例,则创建, 然后返回已创建的实例  
         if(!(self::$_instance instanceof self)){  
          self::$_instance =new self();  
         }   
         return self::$_instance;  
    }  
    public function connect(){  
        if(!self::$_connectSource){  
           self::$_connectSource=mysql_connect(SAE_MYSQL_HOST_M.&#39;:&#39;.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
		   //self::$_connectSource = @mysql_connect($this->_dbConfig[&#39;host&#39;], $this->_dbConfig[&#39;user&#39;], $this->_dbConfig[&#39;password&#39;]);	
        if(!self::$_connectSource){ 
			//如果数据库连接不成功
			//抛出异常,在调用该connnect()函数时,通过try catch 进行捕获
			throw new Exception (&#39;mysql connect error&#39;.mysql_error);
       //die(&#39;mysql connect error&#39;.mysql_error);  
    }  
     mysql_select_db(SAE_MYSQL_DB,self::$_connectSource);  
	 //mysql_select_db($this->_dbConfig[&#39;database&#39;], self::$_connectSource);
     mysql_query("set names UTF8",self::$_connectSource);  
        }  
     return self::$_connectSource;  
    }  
  
}  
Copy after login


2.response.php is used to encapsulate communication data (json or xml)


<?php

class Response {
	const JSON = "json";
	/**
	* 按综合方式输出通信数据
	* @param integer $code 状态码
	* @param string $message 提示信息
	* @param array $data 数据
	* @param string $type 数据类型
	* return string
	*/
	public static function show($code, $message = &#39;&#39;, $data = array(), $type = self::JSON) {
		if(!is_numeric($code)) {
			return &#39;&#39;;
		}

		$type = isset($_GET[&#39;format&#39;]) ? $_GET[&#39;format&#39;] : self::JSON;

		$result = array(
			&#39;code&#39; => $code,
			&#39;message&#39; => $message,
			&#39;data&#39; => $data,
		);

		if($type == &#39;json&#39;) {
			self::json($code, $message, $data);
			exit;
		} elseif($type == &#39;array&#39;) {
			var_dump($result);
		} elseif($type == &#39;xml&#39;) {
			self::xmlEncode($code, $message, $data);
			exit;
		} else {
			// TODO
		}
	}
    
	/**
	* 按json方式输出通信数据
	* @param integer $code 状态码
	* @param string $message 提示信息
	* @param array $data 数据
	* return string
	*/
	public static function json($code, $message = &#39;&#39;, $data = array()) {
		
		if(!is_numeric($code)) {
			return &#39;&#39;;
		}

		$result = array(
			&#39;code&#39; => $code,
			&#39;message&#39; => $message,
			&#39;data&#39; => $data
		);

		echo json_encode($result);
		exit;
	}

	/**
	* 按xml方式输出通信数据
	* @param integer $code 状态码
	* @param string $message 提示信息
	* @param array $data 数据
	* return string
	*/
	public static function xmlEncode($code, $message, $data = array()) {
		if(!is_numeric($code)) {
			return &#39;&#39;;
		}

		$result = array(
			&#39;code&#39; => $code,
			&#39;message&#39; => $message,
			&#39;data&#39; => $data,
		);

		//header("Content-Type:text/xml");
		$xml = "<?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?>\n";
		$xml .= "<root>\n";

		$xml .= self::xmlToEncode($result);

		$xml .= "</root>";
		echo $xml;
	}

	public static function xmlToEncode($data) {

		$xml = $attr = "";
		foreach($data as $key => $value) {
			if(is_numeric($key)) {
				$attr = " id=&#39;{$key}&#39;";
				$key = "item";
			}
			$xml .= "<{$key}{$attr}>";
			$xml .= is_array($value) ? self::xmlToEncode($value) : $value;
			$xml .= "</{$key}>\n";
		}
		return $xml;
	}

}
Copy after login



3.checklogin.php is provided to the client, allowing the client to use GET request, pass in username, passwd to verify login

<?php
//这是app验证登录接口
//访问方式http://****.com/bee/checklogin.php 
if($_GET[&#39;format&#39;]==&#39;xml&#39;){
header("Content-Type:text/xml");}
require_once(&#39;./response.php&#39;);//引入数据封装类
require_once(&#39;./db.php&#39;);//引入数据库类
$username=$_GET[&#39;username&#39;];  
$passwd=$_GET[&#39;passwd&#39;];  
$sql = "select * from user where `username`=&#39;$username&#39; and `passwd`=&#39;$passwd&#39;";  
try{
	$connect=Db::getInstance()->connect(); 
}catch(Exception $e){
    Response::show(403,&#39;数据库连接失败&#39;); 
}

$result=mysql_query($sql,$connect);
$videos=array();
//mysql_fetch_assoc()字段名key植是value,方便客户端解析。每行获取,区别与mysql_fetch_array()
while($video=mysql_fetch_assoc($result)){
$videos[]=$video;
}
//这样就从数据库中获取了数据存到了$videos[]中,接着需要转换成接口数据
if($videos){
Response::show(200,&#39;首页数据获取成功&#39;,$videos);
//这样默认生成了json数据,如果需要xml数据,需要在访问时http://...com/list.php?format=xml
}else{
Response::show(400,&#39;首页数据获取失败&#39;,$videos);
}
Copy after login



-------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ------

The server code has been completed here. It accepts the hhtp get request from the client and verifies whether the user name and password are correct by querying the database. Encapsulate the results into json or xml and output them in the browser. For the client to read.


The following is part of the Android client code:


The layout file will not be displayed, it is just two textviews, two edittexts, and a Button

Go directly to MainActivity.java


package com.example.bee;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

 

public class Login extends Activity {

	/**
	 * 用于登录的界面
	 */
	String result="",user,passwd;
	Handler myhandler;
    EditText userview,passwdview;
    Button login,register;
    Thread t;
    SharedPreferences sp;
    int code;
    String realname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        userview=(EditText) findViewById(R.id.login_edt_user);
        passwdview=(EditText) findViewById(R.id.login_edt_passwd);
        login=(Button) findViewById(R.id.btn_login);
        register=(Button) findViewById(R.id.btn_register);
        sp=getSharedPreferences("login", MODE_PRIVATE);
        String getname=sp.getString("username", null);
		if(getname==null)
		{
			Toast.makeText(Login.this, "sp null", 0).show();
		}else{
			Toast.makeText(Login.this, "sp have", 0).show();
			userview.setText(sp.getString("username", null));
			passwdview.setText(sp.getString("passwd", null));
		}
		
        //登陆按钮点击事件
         login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				  
		         t=new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							user=userview.getText().toString();
							passwd=passwdview.getText().toString();
							URL url=new URL("http://luo.sinaapp.com/e/checklogin.php?username="+user+"&passwd="+passwd);
							HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
							InputStreamReader isr=new InputStreamReader(urlConnection.getInputStream());
							BufferedReader br=new BufferedReader(isr);
							result=br.readLine(); 
							//对获得的json数据进行解析
							try {
								 JSONObject object=new JSONObject(result);
							     code=object.getInt("code");
							     JSONArray ja=  object.getJSONArray("data");
							     String data=ja.getString(0);
							     JSONObject secondobject=new JSONObject(data);
							     realname=secondobject.getString("realname");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							Message m1=myhandler.obtainMessage();
							if(code==400)//登录失败
							{
								m1.what=1;
								myhandler.sendMessage(m1);
							}else if(code==200){//登录成功
								m1.what=2;
								myhandler.sendMessage(m1);
							}else{//其他情况:联网失败,服务器异常等
								m1.what=3;
								myhandler.sendMessage(m1);
							}
							
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				t.start();
			}
		}); 
      //注册点击事件
        /*register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i=new Intent(Login.this,RegisterActivity.class);
				startActivity(i);
				
			}
		});*/
        myhandler=new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		// TODO Auto-generated method stub
        		super.handleMessage(msg);
        		if(msg.what==1){
        		Toast.makeText(Login.this, "用户名或密码不正确", 0).show();
        		} else if(msg.what==2){
        			Toast.makeText(Login.this, "欢迎您:"+realname, 0).show();
        			/*登陆成功将数据写到本地保存下来,以便下次自动额登陆*/
					sp=getSharedPreferences("login", MODE_PRIVATE);
					Editor editor=sp.edit();
					editor.putString("username", user);
					editor.putString("passwd", passwd);
					editor.putString("realname", realname);
					editor.commit();
					Intent i = new Intent(Login.this, MainActivity.class);
					startActivity(i);
					finish();
        		} else {
        			Toast.makeText(Login.this, "网络连接失败", 0).show();
        		}
        	}
        };
       
        
    }


}
Copy after login


If you don’t understand the sharedpreference above, please take a look here:

http://blog.csdn.net/davidluo001/article/details/42290369

If you have any other questions, please leave a message and we will answer them as soon as possible.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/941437.htmlTechArticleAndroid server development (1) Android combined with PHP to realize the connection database verification login function (with all codes attached) Nothing Having said that, go directly to the code. If you don’t understand, leave a message with me below. ...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template