Content
1. API (Application Programming Interface)
2. Project code
__2.1. Creating MySQL Database and Tables
__2.2. Building PHP API Classes
3. Types of API JSON Responses
4. Starting Android Project
__4. 1. Create a new project
__4.2. Create a new package to store all our library files
__4.3. JSON Parser Class
__4.4. SQLite Database Handler Class
__4.5. User Functions Class
__4.6. Designing the Screens
__4.7. Switching between Activites
__4.8. Finally Updating AndroidManifest.xml
1. API (Application Programming Interface)
Accepting requests by GET/POST methods
Interact with PHP classes to get data from database or store in database
Finally will give output in JSON format

2. Project code
2.1. Creating MySQL Database and Tables
http://img.9android.net/Code-Android/login-reigstration-php-sql/android-login-and-registration8.png
Run following query to create database and users table.
- Code: Select all
create table users(
uid int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
); /** Creating Users Table **/
2.2. Building PHP API Classes
To make it minimum i tried to use less number of php files. Following are the files are required to build API in php. You can find description of each file in the below image.
- config.php – This file contains constant variables to connect to database.
- Code: Select all
<!--?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "android_api"); ?-->
- DB_Connect.php – This file is used to connect or disconnect to database.
- Code: Select all
<!--?php class DB_Connect { // constructor function __construct() { } // destructor function __destruct() { // $this--->close();
}
// Connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysql_select_db(DB_DATABASE);
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
- DB_Functions.php – This file contains functions to store user in database, get user from database. You can also add methods like update user, delete user.
user unique id – I am generating unique user id in php using uniqid(”, true) function. Sample user id will be like 4f074eca601fb8.88015924
Encrypted Password – This password is stored using base64_encode method. Each password will need two columns to store in database. One is to store encrypted password and second column is to store salt used to encrypt the password.
- Code: Select all
<!--?php class DB_Functions { private $db; //put your code here // constructor function __construct() { require_once 'DB_Connect.php'; // connecting to database $this--->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
- index.php – This file plays role of accepting requests and giving response. This file accepts all GET and POST requests. On each request it will talk to database and will give appropriate response in JSON format.
- Code: Select all
<!--?php /** * File to handle all API requests * Accepts GET and POST * * Each request will be identified by TAG * Response will be JSON data /** * check for POST request */ if (isset($_POST['tag']) && $_POST['tag'] != '') { // get tag $tag = $_POST['tag']; // include db handler require_once 'include/DB_Functions.php'; $db = new DB_Functions(); // response Array $response = array("tag" =--> $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
echo "Invalid Request";
}
} else {
echo "Access Denied";
}
?>
3. Types of API JSON Responses
The following are the different types of JSON responses generated by API.
Registration Success Response – Success Code = 1 (User Successfully Stored)
- Code: Select all
{
"tag": "register",
"success": 1,
"error": 0,
"uid": "4f074ca1e3df49.06340261",
"user": {
"name": "Ravi Tamada",
"email": "ravi8x@gmail.com",
"created_at": "2012-01-07 01:03:53",
"updated_at": null
}
}
Registration Error Response – Error Code = 1 (Error in storing)
- Code: Select all
{
"tag": "register",
"success": 0,
"error": 1,
"error_msg": "Error occured in Registartion"
}
Registration Error Response – Error Code = 2 (User Already Existed)
- Code: Select all
{
"tag": "register",
"success": 0,
"error": 2,
"error_msg": "User already existed"
}
Login Success Response – Success Code = 1 (User Logged in)
- Code: Select all
{
"tag": "login",
"success": 1,
"error": 0,
"uid": "4f074eca601fb8.88015924",
"user": {
"name": "Ravi Tamada",
"email": "ravi8x@gmail.com",
"created_at": "2012-01-07 01:03:53",
"updated_at": null
}
}
Login Error Response – Error Code = 1 (Login Error – Incorrect username/password)
{
"tag": "login",
"success": 0,
"error": 1,
"error_msg": "Incorrect email or password!"
}

Download full free source code at http://www.dl.9android.net/index.php?act=dl&id=1361279874
Source from http://www.9android.net/android-login-a ... nd-sqlite/


