Friday 8 July 2016

Ajax dependent dropdown (Country, State, City) without DATABASE


Ajax dropdown dependent script. Sometimes we need to develop some good User interface without page reload, then jQuery AJAX comes to rescue.

This is a basic script which use jQuery ajax and some PHP code to process the request.

I develop this without any database connection. For the Country, State, City values I've created some sort of arrays (two-dimentional/multi-dimentional as well).

Dependent dropdown is used in various way, We are going to check how it works with Country, State, City.
When you select country dropdown based on that it will show state dropdown below dynamically.

For that we use on change event, when you change value in country dropdown, an AJAX request fires to external PHP files and shows the results.
Which results in dynamic states in dropdown for that selected country and so on.

We can use database for country, state and city values instead of static arrays.


1. Create a file with a name, for example "ajax_dependent.php" and copy below code in it.
<!DOCTYPE html>
<html>
<head>
    <title>Ajax dependent dropdown (Country, State, City)</title>
    <script type="text/javascript" src="jquery.js"></script>
</head>
<style type="text/css">
    body{font-family: arial;font-size: 14px;}
    .form_container{border: 1px dashed #ccc;float: left;}
    form{width: 400px;padding: 5px;}
    div.input_row{width: 100%;float: left;margin: 5px 0;}
    .input_row label{width: 30%;float: left;}
    .input_row .input_fields{float: left;width: 70%;}
    select{width: 100%;}
</style>
<body>
<script>
    $(document).ready(function(){
        /*script run when you select country from dropdown*/
        $(document).on("change",".select_country",function(){ // You can either use $(".select_country").change(function(){ 
            var country = $(this).val();
            $.ajax({
                type: "POST",
                data: "country="+country,
                url: "process.php",
                success: function(data) {
                    if(data!="") {                
                        $(".select_state").html(data);
                        $(".select_city").html('<option value="">-- Select State --</option>');
                    }else{
                        alert("there's some problem");
                    }
                }
            });
        });
        /*script run when you select state from dropdown*/
        $(document).on("change",".select_state",function(){
            var state = $(this).val();
            $.ajax({
                type: "POST",
                data: "state="+state,
                url: "process.php",
                success: function(data) {
                    if(data!="") {                
                        $(".select_city").html(data);
                    }else{
                        alert("there's some problem");
                    }
                }
            });
        });
    });
</script>
<?php 
    $country_array = array("INDIA","PAKISTAN","CHINA");
?>
<h1>Ajax Dropdowns Country, State, City</h1>
    <div class="form_container">
        <div class="inner_div">
        <form>
            <div class="input_row">
                <label>Country</label>
                <div class="input_fields">
                    <select class="select_country">
                        <option value="">-- Select Country --</option>
                        <?php foreach ($country_array as $countryname) { ?>
                        <option value="<?php echo $countryname;?>"><?php echo $countryname;?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="input_row">
                <label>State</label>
                <div class="input_fields">
                    <select class="select_state">
                        <option value="">-- Select Country --</option>
                    </select>
                </div>
            </div>
            <div class="input_row">
                <label>City</label>
                <div class="input_fields">
                    <select class="select_city">
                        <option value="">-- Select State --</option>
                    </select>
                </div>
            </div>
        </form>
    </div>
    </div>
</body>
</html>

2. Create second file which is used to process Ajax request. Create a file named "process.php" and copy below code to it.
<?php 
    $state_array = array("INDIA"=>array("Delhi","Gujarat","Rajasthan","Maharastra"),
        "PAKISTAN"=>array("Sindh","Punjab"),
        "CHINA"=>array("China state 1","China state 2"));
    $city_array = array("Delhi"=>array("New Delhi","CP","Chanakyapuri"),
        "Gujarat"=>array("Ahmedabad","Katchch","Vadodara","Rajkot"),
        "Rajasthan"=>array("Jaipur","Pushkar","Udaypur"),
        "Maharastra"=>array("Mumbai","Pune","Nagpur"),
        "Sindh"=>array("Sindh City 1","Sindh city 2"),
        "Punjab"=>array("Punjab city 1","Punjab city 2"),
        "China state 1"=>array("China s1 c1","China s1 c2"),
        "China state 2"=>array("China s2 c1","China s2 c2")
        );
    if(isset($_POST['country'])!=""){
        $country = $_POST["country"]; ?>
        <option value="">-- Select State --</option>
        <?php foreach ($state_array[$country] as $statename) { ?>
        <option value="<?php echo $statename;?>"><?php echo $statename;?></option>
        <?php } ?>
    <?php }

    if(isset($_POST['state'])!=""){
        $state = $_POST["state"]; ?>
        <option value="">-- Select City --</option>
        <?php foreach ($city_array[$state] as $cityname) { ?>
        <option value="<?php echo $cityname;?>"><?php echo $cityname;?></option>
        <?php } ?>
    <?php }
?>
<?php } ?> 

You're done. Enjoy the code. Suggestions are welcomed. Tutorial is very basic, there are not any security rules implemented. The code is just for basic understanding of Dropdown manipulation. Please fill free to ask question in the comment box below. Enjoy...!

Friday 31 January 2014

PHP Object Oriented Programming

A better programmer follows object oriented programming principals. It is deal with objects and easy to update the code. In this post I want to explain how to develop user registration and login system implementing with object oriented programming in PHP.

The tutorial contains a folder called include with PHP files.
login.php
registration.php
home.php
include
-- functions.php
-- config.php

Database
Sample database users table columns uid, username, passcode, name and email.
CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
password VARCHAR(50),
name VARCHAR(100),
email VARCHAR(70) UNIQUE
);

functions.php
Contains PHP code class User{} contains functions/methods.
<?php
include_once 'config.php';
class User
{
//Database connect 
public function __construct()
{
$db = new DB_Class();
}
//Registration process 
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
// Login process
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return TRUE;
}
else
{
return FALSE;
}
}
// Getting name
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
// Getting session 
public function get_session()
{
return $_SESSION['login'];
}
// Logout 
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}

}
?>

registration.php
Here $user = new User(); is the class User{} object using this calling method$user->register_user{} and inserting values.
<?php
include_once 'include/functions.php';
$user = new User();
// Checking for user logged in or not
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$register = $user->register_user($_POST['name'], $_POST['username'], $_POST['password'], $_POST['email']);
if ($register)
{
// Registration Success
echo 'Registration successful <a href="login.php">Click here</a> to login';
} else
{
// Registration Failed
echo 'Registration failed. Email or Username already exits please try again';
}
}
?>
//HTML Code
<form method="POST" action="register.php" name='reg' >
Full Name
<input type="text" name="name"/>
Username
<input type="text" name="username"/>
Password
<input type="password" name="password"/>
Email
<input type="text" name="email"/>
<input type="submit" value="Register"/>
</form>

login.php
Calling method $user->check_login{} for login verification. 
<?php
session_start();
include_once 'include/functions.php';
$user = new User();
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = $user->check_login($_POST['emailusername'], $_POST['password']);
if ($login)
{
// Login Success
header("location:login.php");
}
else
{
// Login Failed
$msg= 'Username / password wrong';
}
}
?>
//HTML Code
<form method="POST" action="" name="login">
Email or Username
<input type="text" name="emailusername"/>
Password
<input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>

home.php
<?php
session_start();
include_once 'include/functions.php';
$user = new User();
$uid = $_SESSION['uid'];
if (!$user->get_session())
{
header("location:login.php");
}
if ($_GET['q'] == 'logout')
{
$user->user_logout();
header("location:login.php");
}
?>
//HTML Code
<a href="?q=logout">LOGOUT</a>
<h1> Hello <?php $user->get_fullname($uid); ?></h1>

config.php
Database configuration class DB_class() function __construct() is the method name for the constructor. 
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
class DB_Class 
{
function __construct()
{
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or
die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection)
or die('Database error -> ' . mysql_error());
}
}
?>

How to add new function/method.
For example if you want to get email value. Just include the following function inside class User{} 
public function get_email($uid)
{
$result = mysql_query("SELECT email FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['email'];
}

Print email values.
<?php $user->get_email($uid); ?>