Sunday, November 1, 2015

Connecting Android with PHP, MySQL

 I am going to show how to make a simple Android app that will call a PHP script to perform basic CRUD(Create, Read, Update, Delete) operations. To brief you on the architecture, this is how it works.


First the android app calls a PHP script in order to perform a data operation. The PHP script then connects to the MySQL database to perform the operation.
So the data flows from your Android app to PHP script then finally is stored in your MySQL database.

1. Create MySQL database & Tables
2. Connecting to MySQL database with PHP


db_config.php


<?php


define('DB_USER', "root"); // db user


define('DB_PASSWORD', ""); // db password (mention your db password here)


define('DB_DATABASE', "abc"); // database name


define('DB_SERVER', "localhost"); // db server


?>


db_connect.php

db_connect.php
<?php

/**
* A class file to connect to database
*/
class DB_CONNECT {

// constructor
function __construct() {
// connecting to database
$this->connect();
}

// destructor
function __destruct() {
// closing db connection
$this->close();
}

/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';

// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

// returing connection cursor
return $con;
}

/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}

}

?>