Get Address from Latitude and Longitude using PHP and Google Maps API

On 12/14/2017 Be the first to comment!

Hi! Today let's see how to get address from latitude and longitude using PHP and Google Maps Geocoding API. In general, the process of converting geometric coordinates such as latitude and longitude into address is called reverse geocoding. And the geocoding is just the opposite, converting address into latitude and longitude which we have seen in our previous tutorial. Google Maps provides a separate Geocoding API for the purpose and let's see how to use it with php.

To obtain physical addresses from the API, you have to send http request along with latitude and longitude values.

php get address from latitude longitude google maps api

Getting Address from Latitude and Longitude using Google Maps:

To access Google Maps Geocoding API, you need an http interface through which you can send and receive an http request/response from the api. Here is the sample request you should send to the web service.

http://maps.google.com/maps/api/geocode/json?latlng=40.6781784,-73.9441579

The 'latlng' parameter must be used to provide latitude, longitude values in the url. Also, to get the response as json, you must be specific on your api call.

Below is the reverse geocoding sample response that we get for the above api request,

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "58",
               "short_name" : "58",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Brooklyn Avenue",
               "short_name" : "Brooklyn Ave",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Crown Heights",
               "short_name" : "Crown Heights",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Brooklyn",
               "short_name" : "Brooklyn",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Kings County",
               "short_name" : "Kings County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "11216",
               "short_name" : "11216",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "58 Brooklyn Ave, Brooklyn, NY 11216, USA",
         "geometry" : {
            "location" : {
               "lat" : 40.677978,
               "lng" : -73.94438700000001
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.67932698029149,
                  "lng" : -73.94303801970851
               },
               "southwest" : {
                  "lat" : 40.6766290197085,
                  "lng" : -73.94573598029152
               }
            }
         },
         "place_id" : "ChIJaVKlrIVbwokRhqlQjSdxUHc",
         "types" : [ "street_address" ]
      },
      
      ...
      ...
   ],
   "status" : "OK"
}

The response sends a status flag which you can test to determine the success or failure of the conversion process.

PHP Function to Convert Latitude and Longitude into Address:

Below is the php function to get the address details of the given geographic co-ordinates. You must pass longitude and latitude to the function which in turn makes http request to the api, receive json response, parse and return the formatted address.

<?php
function getAddress($latitude, $longitude)
{
        //google map api url
        $url = "http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude";

        // send http request
        $geocode = file_get_contents($url);
        $json = json_decode($geocode);
        $address = $json->results[0]->formatted_address;
        return $address;
}
?>

Usage:

You have to access the above getAddress() function like this,

<?php
// coordinates
$latitude = '40.6781784';
$longitude = '-73.9441579';
$result = getAddress($latitude, $longitude);
echo 'Address: ' . $result;

// produces output
// Address: 58 Brooklyn Ave, Brooklyn, NY 11216, USA
?>

The php script will output the location as a human-readable address.

API Key:

Without API Key, you're requests credits per day will be very limited. In order to use the API key in each of your requests, you must first activate the Google Maps API and obtain the authentication credentials for it.

Log in to your Google account, go to the API console, activate the 'Google Maps Geocoding API' and get an 'API_KEY'.

Then you can use this key in the url every time you send a request to the api in this way,

http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude&key=API_KEY;

Please note that the sensor param is deprecated in the latest versions of the API. Therefore, it is no longer necessary to attach it with the request URL.

Read Also:

That explains about getting location from latitude and longitude in php using Google Maps Geocoding API. You can use this address info to place a marker on Google Maps. I hope you like this tutorial. If you find this post useful, please share it in your social circle.

Get Latitude and Longitude from Address using PHP and Google Maps API

On 12/12/2017 Be the first to comment!

Hi! In this tutorial, let's see how to get latitude and longitude from address using google maps geocoding api and php. Geocoding is the process of converting physical addresses into geographical coordinates such as latitude and longitude so you can use them to create markers in Google Map. It is also better to provide latitude and longitude when using Google Map API so that you can point to accurate position on the map. To obtain the geocode, we must send an http request to the Google Map Geocoding API along with the formatted address.

php get latitude longitude from address google maps api

How to Get Latitude and Longitude from Address?

The Google Maps Geocoding API is a web service used to obtain geocoding and reverse geocoding of the addresses. And you have to access the api through the HTTP interface.

Here is the sample request you have to send to Geocoding API to get latitude and longitude coordinates.

The API provides a response in both json and xml format. Since json is cross platform compatible, let us inform the api to send the response as json.

// api request
http://maps.google.com/maps/api/geocode/json?address=Brooklyn,+NY,+USA

And the above http request will provide a json response that looks something like this,

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Brooklyn",
               "short_name" : "Brooklyn",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Kings County",
               "short_name" : "Kings County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Brooklyn, NY, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.739446,
                  "lng" : -73.83336509999999
               },
               "southwest" : {
                  "lat" : 40.551042,
                  "lng" : -74.05663
               }
            },
            "location" : {
               "lat" : 40.6781784,
               "lng" : -73.94415789999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.739446,
                  "lng" : -73.83336509999999
               },
               "southwest" : {
                  "lat" : 40.551042,
                  "lng" : -74.05663
               }
            }
         },
         "place_id" : "ChIJCSF8lBZEwokRhngABHRcdoI",
         "types" : [ "political", "sublocality", "sublocality_level_1" ]
      }
   ],
   "status" : "OK"
}

Now let's see how to use this geocoding api in php to get latitude and longitude details of an address.

PHP Function to Get Geocoding from Google Maps:

Here is the php function to get geocoding information. The function takes up address of a location, sends an http request to the google map api, decodes the json response and extracts and returns the coordinates of latitude and longitude.

<?php
function getGeoCode($address)
{
        // geocoding api url
        $url = "http://maps.google.com/maps/api/geocode/json?address=$address";
        // send api request
        $geocode = file_get_contents($url);
        $json = json_decode($geocode);
        $data['lat'] = $json->results[0]->geometry->location->lat;
        $data['lng'] = $json->results[0]->geometry->location->lng;
        return $data;
}
?>

Function Usage:

You have to call the getGeoCode() function like below.

<?php
$address = 'Brooklyn, NY, USA';
$address = str_replace(' ', '+', $address);
$result = getGeoCode($address);
echo 'Latitude: ' . $result['lat'] . ', Longitude: ' . $result['lng'];

// produces output
// Latitude: 40.6781784, Longitude: -73.9441579
?>

Please note that the address you specify must be an actual one and should be formatted by replacing the space character with the '+' operator.

Using API Key:

To use the API key, you must log in to your Google account, activate the 'Google Maps Geocoding API' on your account and get an 'API_KEY'.

Then you can include your key using the key parameter on each request like this,

https://maps.googleapis.com/maps/api/geocode/json?address=FORMATTED_ADDRESS&key=YOUR_API_KEY

The earlier versions of the API, includes sensor parameter to determine if your application uses sensor to find the user's location or not. The parameter is deprecated and no longer necessary with the API call.

Read Also:

That explains about getting latitude and longitude coordinates from a physical address in php using Google Maps Geocoding API. Once you get the geocode, you can use them to position the map. I hope you like this tutorial. If you find it useful, please share the post on your social circle.

How to Update Data in Database using ID in CodeIgniter

On 12/12/2017 7 Comments so far

How to update data in database using id in codeigniter?. Using codeigniter update query will let you perform update operation on database. In the previous post, I explained you about how to insert data into database using codeigniter and bootstrap. This tutorial will demonstrates you about updating database records in codeigniter.

CodeIgniter DB Update is going to be very easy as we have made required ground coding in CodeIgniter Database Insert tutorial. The update model, controller, and the view files will share some of the same features like insert along with fewer coding of its own.

Update Data in Database using ID in CodeIgniter

If you are a regular reader of Koding Made Simple, then you would have known, in most of my tutorials I use Twitter Bootstrap CSS Framework to design the front end. In this codeigniter database update tutorial too, I'm going to combine bootstrap with codeigniter to design the update form.

Setting up MySQL Database

For DB, I'm going to use the same employee database used in codeigniter insert tutorial. Run this sql file in MySQL to create the DB.

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

CREATE TABLE IF NOT EXISTS `tbl_department` (
  `department_id` int(4) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(80) NOT NULL,
  PRIMARY KEY (`department_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `tbl_department` (`department_id`, `department_name`) VALUES
(1, 'Finance'),
(2, 'HQ'),
(3, 'Operations'),
(4, 'Marketing'),
(5, 'Sales');

CREATE TABLE IF NOT EXISTS `tbl_designation` (
  `designation_id` int(4) NOT NULL AUTO_INCREMENT,
  `designation_name` varchar(50) NOT NULL,
  PRIMARY KEY (`designation_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `tbl_designation` (`designation_id`, `designation_name`) VALUES
(1, 'VP'),
(2, 'Manager'),
(3, 'Executive'),
(4, 'Trainee'),
(5, 'Senior Executive');

CREATE TABLE IF NOT EXISTS `tbl_employee` (
  `employee_id` int(4) NOT NULL AUTO_INCREMENT,
  `employee_no` int(6) NOT NULL,
  `employee_name` varchar(60) NOT NULL,
  `department_id` int(4) NOT NULL,
  `designation_id` int(4) NOT NULL,
  `hired_date` date NOT NULL,
  `salary` int(10) NOT NULL,
  PRIMARY KEY (`employee_id`),
  UNIQUE KEY `employee_no` (`employee_no`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

INSERT INTO `tbl_employee` (`employee_id`, `employee_no`, `employee_name`, `department_id`, `designation_id`, `hired_date`, `salary`) VALUES
(1, 1001, 'Steve John', 1, 2, '2013-08-01', 60000);

The Model File ('models/employee_model.php')

<?php
/* 
 * File Name: employee_model.php
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class employee_model extends CI_Model
{
    function __construct()
    {
        //Call the Model constructor
        parent::__construct();
    }

    //fetch employee record by employee no
    function get_employee_record($empno)
    {
        $this->db->where('employee_no', $empno);
        $this->db->from('tbl_employee');
        $query = $this->db->get();
        return $query->result();
    }
    
    //get department table to populate the department name dropdown
    function get_department()
    { 
        $this->db->select('department_id');
        $this->db->select('department_name');
        $this->db->from('tbl_department');
        $query = $this->db->get();
        $result = $query->result();

        //array to store department id & department name
        $dept_id = array('-SELECT-');
        $dept_name = array('-SELECT-');

        for ($i = 0; $i < count($result); $i++)
        {
            array_push($dept_id, $result[$i]->department_id);
            array_push($dept_name, $result[$i]->department_name);
        }
        return $department_result = array_combine($dept_id, $dept_name);
    }
    
    //get designation table to populate the designation dropdown
    function get_designation()     
    { 
        $this->db->select('designation_id');
        $this->db->select('designation_name');
        $this->db->from('tbl_designation');
        $query = $this->db->get();
        $result = $query->result();

        $designation_id = array('-SELECT-');
        $designation_name = array('-SELECT-');

        for ($i = 0; $i < count($result); $i++)
        {
            array_push($designation_id, $result[$i]->designation_id);
            array_push($designation_name, $result[$i]->designation_name);
        }
        return $designation_result = array_combine($designation_id, $designation_name);
    }
}
?>

Read: How to integrate Twitter Bootstrap 3 with PHP CodeIgniter Framework

As said earlier, the model file will be similar to the Codeigniter Bootstrap Insert example but with one additional method to fetch the employee record for the given employee number. Rest of the two methods get_department() and get_designation() will be the same as insert. These two methods are used to populate the drop down list in the update form.

The Controller File ('controllers/updateEmployee.php')

<?php
/* 
 * File Name: updateEmployee.php
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class updateEmployee extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->database();
        $this->load->library('form_validation');
        //load the employee model
        $this->load->model('employee_model');
    }
    
    //index function
    function index($empno)
    {
        $data['empno'] = $empno;

        //fetch data from department and designation tables
        $data['department'] = $this->employee_model->get_department();
        $data['designation'] = $this->employee_model->get_designation();

        //fetch employee record for the given employee no
        $data['emprecord'] = $this->employee_model->get_employee_record($empno);    

        //set validation rules
        $this->form_validation->set_rules('employeename', 'Employee Name', 'trim|required|xss_clean|callback_alpha_only_space');
        $this->form_validation->set_rules('department', 'Department', 'callback_combo_check');
        $this->form_validation->set_rules('designation', 'Designation', 'callback_combo_check');
        $this->form_validation->set_rules('hireddate', 'Hired Date', 'required');
        $this->form_validation->set_rules('salary', 'Salary', 'required|numeric');

        if ($this->form_validation->run() == FALSE)
        {   
            //fail validation
            $this->load->view('update_employee_view', $data);
        }
        else
        {
            //pass validation
            $data = array(
                'employee_name' => $this->input->post('employeename'),
                'department_id' => $this->input->post('department'),
                'designation_id' => $this->input->post('designation'),
                'hired_date' => @date('Y-m-d', @strtotime($this->input->post('hireddate'))),
                'salary' => $this->input->post('salary'),
            );

            //update employee record
            $this->db->where('employee_no', $empno);
            $this->db->update('tbl_employee', $data);

            //display success message
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Employee Record is Successfully Updated!</div>');
            redirect('updateEmployee/index/' . $empno);
        }
    }
    
    //custom validation function for dropdown input
    function combo_check($str)
    {
        if ($str == '-SELECT-')
        {
            $this->form_validation->set_message('combo_check', 'Valid %s Name is required');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    //custom validation function to accept only alpha and space input
    function alpha_only_space($str)
    {
        if (!preg_match("/^([-a-z ])+$/i", $str))
        {
            $this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}
?>

Read: How to Create Login Form in CodeIgniter, MySQL and Twitter Bootstrap

Create the controller file and load the necessary codeigniter libraries along with employee model. Here we update the employee records based on employee number field. Pass it as a url parameter when we call the controller like this,

http://yourdomain.com/ci-demo/index.php/updateEmployee/index/1001

The last uri segment '1001' is the argument to the controller index() function.

Pre Populate the CodeIgniter Update Form with Database Data

Next call back all the three model methods get_department(), get_designation(), get_employee_record() and store them in the data array to pass it to the view file.

Add Form Validation to CodeIgniter Update Form

Next set the validation rules for the form input fields. I have disabled the employee number field to restrict the user from editing it. So no validation for that field.

Use CodeIgniter Update Query to Edit Database Record

Next run the validation rule on the submitted values and display the error message on failed validation. Else move the post data into an array and use codeigniter update query statement, $this->db->update() to update the particular employee record provided by $this->db->where() statement.

CodeIgniter-Update-Database-Form-Validation-Error

Upon successful db update, we notify the user by displaying a message using set_flashdata() method.

CodeIgniter-Update-Query-Success-Message

The View File ('views/update_employee_view.php')

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Update Database Demo | CodeIgniter Update Query</title>
    <!--link the bootstrap css file-->
    <link href="<?php echo base_url("assets/bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
    <!-- link jquery ui css-->
    <link href="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
    <!--include jquery library-->
    <script src="<?php echo base_url('assets/js/jquery-1.10.2.js'); ?>"></script>
    <!--load jquery ui js file-->
    <script src="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.js'); ?>"></script>
        
    <style type="text/css">
    .colbox {
        margin-left: 0px;
        margin-right: 0px;
    }
    </style>
    
    <script type="text/javascript">
    //load datepicker control onfocus
    $(function() {
        $("#hireddate").datepicker();
    });
    </script>
    
</head>
<body>
<br>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 well">
        <legend>CodeIgniter Update Database Demo</legend>
        <?php 
        $attributes = array("class" => "form-horizontal", "id" => "employeeform", "name" => "employeeform");
        echo form_open("updateEmployee/index/" . $empno, $attributes);?>
        <fieldset>
            
            <div class="form-group">
            <div class="row colbox">
            
            <div class="col-md-4">
                <label for="employeeno" class="control-label">Employee Number</label>
            </div>
            <div class="col-md-8">
                <input id="employeeno" name="employeeno" placeholder="employeeno" type="text" disabled="disabled" class="form-control"  value="<?php echo $emprecord[0]->employee_no; ?>" />
                <span class="text-danger"><?php echo form_error('employeeno'); ?></span>
            </div>
            </div>
            </div>

            <div class="form-group">
            <div class="row colbox">
            <div class="col-md-4">
                <label for="employeename" class="control-label">Employee Name</label>
            </div>
            <div class="col-md-8">
                <input id="employeename" name="employeename" placeholder="employeename" type="text" class="form-control"  value="<?php echo set_value('employeename', $emprecord[0]->employee_name); ?>" />
                <span class="text-danger"><?php echo form_error('employeename'); ?></span>
            </div>
            </div>
            </div>
            
            <div class="form-group">
            <div class="row colbox">
            <div class="col-md-4">
                <label for="department" class="control-label">Department</label>
            </div>
            <div class="col-md-8">
            
                <?php
                $attributes = 'class = "form-control" id = "department"';
                echo form_dropdown('department',$department,set_value('department', $emprecord[0]->department_id),$attributes);?>
                <span class="text-danger"><?php echo form_error('department'); ?></span>
            </div>
            </div>
            </div>

            <div class="form-group">
            <div class="row colbox">
            <div class="col-md-4">
                <label for="designation" class="control-label">Designation</label>
            </div>
            <div class="col-md-8">
            
                <?php
                $attributes = 'class = "form-control" id = "designation"';
                echo form_dropdown('designation',$designation, set_value('designation', $emprecord[0]->designation_id), $attributes);?>
                
                <span class="text-danger"><?php echo form_error('designation'); ?></span>
            </div>
            </div>
            </div>
            
            <div class="form-group">
            <div class="row colbox">
            <div class="col-md-4">
                <label for="hireddate" class="control-label">Hired Date</label>
            </div>
            <div class="col-md-8">
                <input id="hireddate" name="hireddate" placeholder="hireddate" type="text" class="form-control"  value="<?php echo set_value('hireddate', @date('d-m-Y', @strtotime($emprecord[0]->hired_date))); ?>" />
                <span class="text-danger"><?php echo form_error('hireddate'); ?></span>
                
            </div>
            </div>
            </div>
            
            <div class="form-group">
            <div class="row colbox">
            <div class="col-md-4">
                <label for="salary" class="control-label">Salary</label>
            </div>
            <div class="col-md-8">
                <input id="salary" name="salary" placeholder="salary" type="text" class="form-control"  value="<?php echo set_value('salary', $emprecord[0]->salary); ?>" />
                <span class="text-danger"><?php echo form_error('salary'); ?></span>
            </div>
            </div>
            </div>
            
            <div class="form-group">
            <div class="col-sm-offset-4 col-md-8 text-left">
                <input id="btn_update" name="btn_update" type="submit" class="btn btn-primary" value="Update" />
                <input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
            </div>
            </div>
        </fieldset>
        <?php echo form_close(); ?>
        <?php echo $this->session->flashdata('msg'); ?>
        </div>
    </div>
</div>
</body>
</html>

The codeigniter view contains the update form. Here we receive employee record fetched from the database and populate the form fields on loading. After the user submits the edited form, on successful form field validation we update the database record using codeigniter update query.

To populate the update form field values from database on load, I have passed them as second parameter to set_value() functions. Which initially will load the database value and in case of validation error, it will re-populate the user submitted values to the form fields.

Read Also:

That explains about updating data from database using id in codeigniter and bootstrap frameworks. I hope you find this PHP Codeigniter Database Update Tutorial useful.

How to Get User IP Address in CodeIgniter

On 12/12/2017 Be the first to comment!

Hi, this quick post discusses about getting user ip address in php codeigniter framework. Say you have an application built on code igniter mvc and you want to collect visitor's ip address. The easiest solution is to use the codeigniter's input class.

CodeIgniter input class serves two important purposes. 1. It ensures security by pre-processing the global input data and 2. It does provide helper functions to fetch the input data and pre-process it.

how-to-get-user-ip-address-in-codeigniter

Unlike other codeigniter libraries, we don't have to manually initialize this input class as it is done automatically by the system.

Get IP Address of the User in CodeIgniter

The input class provides two built-in functions namely ip_address() and valid_ip() to process the ip address.

To get the ip address of the current user use it like this,

$ip = $this->input->ip_address();

This returns the current user's ip address. It returns 0.0.0.0 if the ip is not valid.

Validate IP Address

With the help of the function valid_id($ip) you can validate any ip address. It takes up the ip address as parameter and returns TRUE if it is valid or FALSE if not valid.

You can check for valid ip like this,

echo ($this->input->valid_ip($ip)?'Valid':'Not Valid');

It also takes up an optional second parameter, a string value of 'IPv4' or 'IPv6' to specify an IP format. If it is not provided it will check for both formats by default.

Read Also:

That was all about getting the client/user ip address in codeigniter.

Autocomplete Textbox using HTML5 Datalist, PHP and MySQL Example

On 12/12/2017 6 Comments so far

Autosuggest Textbox is a cool technique to enhance user experience in websites. It's a google like search box which pops up suggestions while you type and lets you choose the word(s) without typing it completely. Usually this feature requires third party tools like jquery plug-ins to implement but thanks to HTML5, you can do it with plain html and php alone. In this tutorial, I'm going to show you, how easy it is to integrate HTML5 auto complete textbox from database using PHP and MySQL.

Autocomplete Textbox from Database using HTML5 and PHP

The HTML5 DATALIST element adds up autocomplete feature to ordinary textboxes and it takes up several options similar to SELECT element. To implement auto suggest from database, we should fetch the data and populate it to the datalist options. Finally integrate this datalist to a textbox element and we are done. Let's see how to do it in php and mysql.

Step-1: Connect to MySQL Database in PHP

First establish the connection to mysql database in php.

<?php
//connect to mysql database
$connection = mysqli_connect("localhost","username","password","store") or die("Error " . mysqli_error($connection));
?>

Step-2: Fetch the Required Data from MySQL Table

Now fetch the required mysql table field data from database. Here I wish to select the list of category names from the 'category' table.

<?php
//fetch data from database
$sql = "select cname from category";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
?>

Step-3: Create Datalist with MySQL Data

Next create a datalist element, loop through the mysql resultset and add the category names one by one to the datalist options.

<datalist id="categoryname">
    <?php while($row = mysqli_fetch_array($result)) { ?>
        <option value="<?php echo $row['cname']; ?>"><?php echo $row['cname']; ?></option>
    <?php } ?>
</datalist>

Step-4: Integrate Datalist with a Textbox

Next create an input element and set its LIST attribute to datalist's ID.

<input type="text" id="pcategory" autocomplete="off" list="categoryname">

It simply binds the textbox with the datalist OPTIONS and suitable suggestions pops up when the user type something in the box. We also used autocomplete = "off" to disable the browser's default autocomplete feature for proper functioning of our own autosuggest feature.

Step-5: Close the Database Connection

Finally close the mysql database connection we have established earlier.

<?php mysqli_close($connection); ?>

That's it. Now go and check it in your browser and see the auto complete textbox works like a charm (Only in HTML5 supported browsers).

autosuggest-textbox-in-html5-php-mysql-example
Autocomplete Textbox in HTML5 Example

Complete Code for HTML5 Autocomplete Textbox

<?php
//connect to mysql database
$connection = mysqli_connect("localhost","username","password","store") or die("Error " . mysqli_error($connection));

//fetch data from database
$sql = "select cname from category";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
?>
<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete Textbox in HTML5 PHP and MySQL</title>
</head>
<body>
    <label for="pcategory">Product Category</label>
    <input type="text" list="categoryname" autocomplete="off" id="pcategory">
    <datalist id="categoryname">
        <?php while($row = mysqli_fetch_array($result)) { ?>
            <option value="<?php echo $row['cname']; ?>"><?php echo $row['cname']; ?></option>
        <?php } ?>
    </datalist>
    <?php mysqli_close($connection); ?>
</body>
</html>

Also Read: How to Insert JSON File into MySQL Database using PHP

Don't Miss: How to Insert CSV File into MySQL Database using PHP

And that was all about implementing autocomplete textbox in html5 and php. If you want the auto complete with more styling options, then using jQuery UI plug-in is the best option. Read this tutorial to learn about using jquery ui for autocomplete textbox in php and mysql.

How to Install and Setup PHP CodeIgniter Framework in XAMPP Localhost

On 12/12/2017 4 Comments so far

Though I have written several php codeigniter tutorials in the past, this post is solely aimed at absolute beginners who want to set foot in this php mvc framework. The lure of codeigniter is its pretty small learning curve and the flexibility to accommodate small to large web applications. MVC frameworks demands structured workflow and it's necessary to configure properly for them to work. This codeigniter tutorial will walk you through step by step on how to install and setup the codeigniter framework in xampp stack.

how-to-install-setup-php-codeigniter-framework-xampp

Install CodeIgniter in XAMPP

First download codeigniter latest version and extract its contents to the "htdocs" folder of XAMPP. Rename the folder to some application name such as "ci_demo".

CodeIgniter Folder Structure

CodeIgniter follows a certain folder (directory) structure and consists of three folders namely "system", "application" and "user_guide".

how-to-setup-codeigniter-folder-structure
PHP CodeIgniter Folder Structure

  1. System: The system folder contains the core application files and should not be bothered. When you want to upgrade to newer version, you can easily replace this system folder alone in your app.
  2. Application: The application folder is where we place the coding files and it contains a bunch of sub-directories to support the application development. Of them the three main directories are the model, view and the controller.
  3. User_Guide: This folder contains the well documented user manual for the codeigniter framework.

Note: Remove the "user_guide" folder when you move the application to production environment.

Configure and Setup the CodeIgniter Environment

Having the codeigniter app in place we should make it run by editing few configuration settings.

  1. Open the applicaion/config/config.php file.
  2. We need the codeigniter application to point to the proper base url. For that set the "base_url" array value to the following.

$path = "http://" . $_SERVER['HTTP_HOST'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $path;

The above code will automatically detect the base url path of the application wherever it is located.

CodeIgniter URL Structure

CodeIgniter generates search engine optimized URLs. Its URL structure looks like this,

<base_url>/index.php/<controller_name>/<controller_function_name>

For example if you want to access a "login" controller in localhost, then the url should be something like this,

http://localhost/ci_demo/index.php/login

To generate clean urls without "index.php" in the middle, you have to rewrite them in the ".htaccess" file. Check here to learn how to remove index.php from codeigniter url structure.

Connect to Database in CodeIgniter

If you want to use database in the codeigniter application, then you have to configure the connection details in the application/config/database.php file.

Here are the connectivity details for MySQL Database.

$db['default']['hostname'] = 'localhost'; //server
$db['default']['username'] = 'username'; //mysql username
$db['default']['password'] = 'mysql_password'; //mysql password
$db['default']['database'] = 'employee'; //database name
$db['default']['dbdriver'] = 'mysql';

Related Read: How to Connect with Multiple Databases in CodeIgniter

Also Read: How to Create Login System in CodeIgniter, MySQL and Bootstrap

Now we have setup the codeigniter environment and it's time to try out something more. Check out our codeigniter tutorials section for more advanced articles on the topic.

Search Multidimensional Array for Key Value in PHP

On 12/12/2017 1 Comment so far

Arrays are generally used to store and manipulate data with ease and known to be one of the core building blocks of PHP Programming. When properly used, arrays are a great tool to process large amount of data efficiently - be it from database server or from a third-party source. But they can become nasty once you start working with multidimensional array which by itself is an array of arrays i.e., every element of the array turns out as an array. Below example is a good representation of a multi-dimensional array.

PHP Multi Dimensional Array

$color = Array (
    ('r') => Array (
        ('red') => 255,
        ('green') => 0,
        ('blue') => 0
    ),
    ('g') => Array (
        ('red') => 0,
        ('green') => 255,
        ('blue') => 0
    ),
    ('b') => Array (
        ('red') => 0,
        ('green') => 0,
        ('blue') => 255
    )
);

Searching through this sort of multidimensional array for some key or value will be a challenge you should face as a php beginner. Here we'll see how to search multidimensional array for key and value efficiently in php.

PHP Search Array for Key

If you want to retrieve the value of a specific key, then it's pretty straightforward and can be accessed like this,

<?php
print_r($color['r']);

// output
// Array ( [red] => 255 [green] => 0 [blue] => 0 )
?>

But searching through the nested array values needs some more effort and here I have given two different ways to handle it.

Method 1: Search Multidimensional Array for Key Value

This method applies to PHP versions <= 5.4 since there are no built-in functions for performing this sort of array search. We have to do it manually and here is the PHP function to search for the nested array values and return the key from the multidimensional array.

<?php
// php function to search multi-dimensional array
function searchArray($key, $st, $array) {
   foreach ($array as $k => $v) {
       if ($v[$key] === $st) {
           return $k;
       }
   }
   return null;
}

// define multidimensional array
$color = Array (
    ('r') => Array (
        ('red') => 255,
        ('green') => 0,
        ('blue') => 0
    ),
    ('g') => Array (
        ('red') => 0,
        ('green') => 255,
        ('blue') => 0
    ),
    ('b') => Array (
        ('red') => 0,
        ('green') => 0,
        ('blue') => 255
    )
);

// search for key
echo "The Key is " . searchArray('blue', 255, $color);

// output
// The Key is b
?>

Method 2: Applies for PHP V5.5 and Above

As for PHP versions 5.5+ the process of searching multidimensional array is a one-liner code.

<?php
echo "The Key is " . array_search(255, array_column($color, 'blue'));

// output
// The Key is b
?>
  • The function array_search() searches the given array for a specific value and returns it's key.
  • The function array_column() returns the values of the specified column from the array.

That explains about searching multidimensional array for key and value in php language.

Contact Form

Name

Email *

Message *