How to Create Custom Library in CodeIgniter

On 4/25/2018 Be the first to comment!

Hi, today let's see how to create custom library in codeigniter. CodeIgniter offers a rich set of libraries and helpers for robust application development. In general, a library is a class file used to group similar functionalities into a single file. Now we can do the same with helper but the libraries have their own object to store relevant data.

Below I'll show you how to create your own class libraries in CI. You must store these library files inside the 'application/libraries' folder. This will keep them separate from the native libraries of the framework.

create custom library in codeigniter

CodeIgniter - Create Custom Library:

CodeIgniter is a flexible MVC framework and allows you to,

  1. Create new custom libraries.
  2. Extend existing libraries to include additional functionalities to them.
  3. Replace native libraries completely with your own version.

I'm going to show you an example where I create a custom library to export the database table as a json string.

STEP-1) Create a library named 'Mylib.php' inside the 'application/libraries' folder. Make sure the file name matches the class name.

Mylib.php

<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

class Mylib
{
    public function to_json($tblname)
    {
        $CI =& get_instance();
        $CI->load->database();
        $query = $CI->db->get($tblname);
        return json_encode($query->result(), JSON_PRETTY_PRINT);
    }
}
?>

In the 'Mylib' class, I have added a member function to_json() which takes up a database table name as a parameter, fetch and return the data as json.

STEP-2) Next we need a controller file to test the library. So create a controller 'TestController.php' within 'application/controllers' folder.

TestController.php

<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

class TestController extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }
    
    function index()
    {
        // code
    }
}
?>

STEP-3) Now load the library within the controller's index() function.

$this->load->library('mylib');

You can also auto load the library inside 'application/config/autoload.php' file. Just look for the line, $autoload['libraries'] and add the library name. Auto loading will make it available for the entire application.

STEP-4) Then call the to_json() function to export the database table as json.

$json = $this->mylib->to_json('customers');
print '<pre>' . $json . '</pre>';

Now running the 'TestController' will output the data from the given table as a json string on the browser.

This is just a simple example of what a custom library can do.

Extending a Native Library:

Sometimes you may want to include some additional functions to a native library. In such case you can just extend the library like this,

class MY_Email extends CI_Email
{

    public function __construct()
    {
        parent::__construct();
    }
    
    public function my_function()
    {
        // code goes here
    }
}

Please note that while extending a library you must set the prefix 'MY_' before the class name.

And you can change this prefix inside 'application/config/config.php' file. Just search for the below line and replace it with your choice of prefix.

$config['subclass_prefix'] = 'MY_';

To use my_function() in your application, load the 'email' library like you always do and access the function like this,

$this->load->library('email');
$this->email->my_function();

Replacing the Native Library:

In case you want to rewrite an entire native library, you can simply replace it with your own version. For example, to replace the 'Email' library, create a file 'Email.php' inside 'application/libraries' folder and declare the class like this,

class CI_Email
{
    // code
}

And to use the class, you can simply load it on your controller or view like this,

$this->load->library('email');
Also Read:

That explains about creating custom libraries in codeigniter. I have also discussed about other ways of working with libraries. Just make sure to place all your library files inside 'application' > 'libraries' path and you are good to go. I hope you find this tutorial useful. Please share it on social media if you like it.

How to Import CSV File into MySQL with LOAD DATA INFILE

On 4/18/2018 Be the first to comment!

I tried to import a csv file into mysql with php script. It is a simple solution if you have a small set of data to import. But if you have hundreds of thousands of records, don't even think about it. You need something different to read through a large dataset quickly. MySQL's LOAD DATA INFILE command works like a charm and can be executed from the command line.

Using LOAD DATA INFILE allows you to load csv or any other delimited data file to the mysql table with a single command. It comes with several options and we will see below what they are and how to use them to import the csv data set into the mysql table.

Using LOAD DATA INFILE Command:

The LOAD DATA INFILE command in mysql loads data from a file into the table at high speed. The file path specified must be absolute or relative.

1. Importing CSV File into MySQL:

Let's say we have a mysql table 'customers' with the following structure.

MySQL Table: Customers
CREATE TABLE `customers`(
    `id` INT(8) NOT NULL ,
    `name` VARCHAR(30) NOT NULL ,
    `email` VARCHAR(40) NOT NULL ,
    `location` VARCHAR(25) NOT NULL ,
    PRIMARY KEY (`id`)
);

And a csv file customers.csv with data that we want to insert into the 'customers' table.

CSV File: Customers.csv
csv file to import into mysql

Now to import the csv data into the table, use the following sql statement.

LOAD DATA INFILE 'c:/tmp/customers.csv'
INTO TABL    E customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Executing the above sql will import records to the given 'customers' table.

customers mysql table after running load data infile command

Our csv file has a column header as the first row, so we used the option IGNORE 1 LINES which will skip the first row. If you don't have the column header, don't use it.

Also make sure the file path is correct. You can use the format 'c:/tmp/customers.csv' or 'c:\\tmp\\customers.csv'.

This method will only work when your mysql table has the same sequence of columns as of the csv file.

2. Importing File with Different Column Sequence from Table:

Consider the scenario where your table and csv file column sequence are different. In this case, you must explicitly specify the order of the column name to ensure that the data is imported correctly.

LOAD DATA INFILE 'c:/tmp/customers.csv'
INTO TABLE tbl_customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(id,name,email,location);

3. Importing Data to Remote MySQL Database Server:

If you have your file on the local machine and not on the server, use the word LOCAL. This will import file from the client (local system) to a remote mysql database server.

LOAD DATA LOCAL INFILE 'c:/tmp/customers.csv'
INTO TABLE tbl_customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(id,name,email,location);

When you include the LOCAL option, the file is expected to be located on the client and not on the server.

You can also use the mysqlimport utility to load csv data into the database. It's very similar to LOAD DATA INFILE, except that mysqlimport supports multiple file loading and the latter does not.

Read Also:

If you have a large dataset to import, go for the LOAD DATA INFILE command, as it is extremely faster than doing it with any other script. I hope this tutorial is useful to you. Please share it on social media if you like it.

How to Add Select All Options to jQuery Select2 Plug-in

On 4/09/2018 Be the first to comment!

Hi, in this post let's see how to add select all options to jQuery Select2 plugin. Select2 is an excellent alternative to the standard HTML selection box that supports all its functions and provides greater flexibility. The plug-in is easy to setup and use. It supports multiple selection options where the selected elements will be added as pills to the top text box. You can also tag, search and load remote data-sets to select2 control.

Below we will see how to use select2 in your web projects, and select all options at once by ticking a check box using jquery.

jquery select2 select all options on click

How to Use Select2 jQuery Plug-in?

To implement Select2 plug-in in your projects, create a regular drop-down box with html markup as usual.

HTML:

<select id="states" style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

This would produce a select box like this,

standard html select box example

Now load the library files for jquery and select2 on the html page. Do it only once on a page.

CSS:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

JS:

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

Finally bind the select2() method to the dropdown in this way,

$(document).ready(function() {
    $('#states').select2();
});

It will initialize the select2 control and convert the plain dropdown to this,

select2 single select example

Please note that you must wrap your code within the $(document).ready() block. This will ensure that the DOM is ready before initializing the select2 control.

Select2 Multiple Select Box:

Select2 also supports multiple selection option. All you have to do is to declare the multiple attribute to the input. This will add the selected options as pills to the text box at the top of the control.

Example:

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
});
</script>

The above example will produce a dropdown box like this,

select2 multi select example

Add Select All Option to jQuery Select2:

Select2 also supports selecting all options at once from the list. Here we'll see how to select all the options when the user ticks the 'Select All' checkbox.

First create the markup for the multi-value select box and a check box for selecting all option.

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<input id="chkall" type="checkbox" >Select All

Now add this java script to the page.

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
    
    $("#chkall").click(function(){
        if($("#chkall").is(':checked')){
            $("#states > option").prop("selected", "selected");
            $("#states").trigger("change");
        } else {
            $("#states > option").removeAttr("selected");
            $("#states").trigger("change");
        }
    });
});
</script>

The above script will be executed by onclick() event of the check box. If checked, the script will set all the options of the select control as selected.

If you think this will alone do the job, you're wrong. This will simply keep all items in the dropdown selected, but will not add the selected items to the top of the control. For that we have to explicitly trigger the 'change' event.

select2 select all options example

Read other tutorials of select2,

That explains about jquery select2 and selecting all the options at once on click of the checkbox. The plugin offers so many customizations and adds flexibility to the standard html select box. I hope you like this tutorial. Meet you in another interesting post. Good day!

Send HTML Email in PHP via SMTP

On 4/06/2018 5 Comments so far

Hi! Welcome to Koding Made Simple. Today we'll see how to send html email in php. PHP's mail() function is simple and effective and let you send emails with text/html contents and with attachments. Though it has some shortcomings compared to other mailer libraries like PHPMailer, it does the job and comes in-built with PHP package. Plain text emails are good enough, but the ability to send html emails is more powerful in email marketing and other promotions.

HTML emails include html tags and let you add images, format texts and other eye-catching call-to-action buttons etc. But you have to add additional headers for mailing them.

php-send-html-email-via-smtp

Using SMTP for Sending Email

You can send mails via third party Mail Servers but you need authentication first. That is if you want to send email via Gmail in php, then you must have a working gmail account and provide the accounts email-id and password for authentication. We'll see how to set up the php configuration for sending email via gmail smtp server.

How to Send HTML Email in PHP Using Gmail SMTP

You need to change the settings in two places i.e., php.ini and sendmail.ini files. You must remove the ; at the starting of the line to enable the settings in these files. Please note the configuration is given for the xampp package. Open 'php.ini' file located at C:\xampp\php\php.ini and edit the settings like below.

php.ini

[mail function]
SMTP = smtp.gmail.com
smtp_port = 587
sendmail_from = christmascontest@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
Next open the 'sendmail.ini' file located at C:\xampp\sendmail\sendmail.ini and make the below changes.

sendmail.ini

smtp_server = smtp.gmail.com
smtp_port = 587
auth_username = christmascontest@gmail.com
auth_password = christmascontest
force_sender = christmascontest@gmail.com

Save the files and restart apache server for the changes to reflect. Now you are ready to send send html email using php mail() function.

Create a php file and write down the below php mailer code to it and save.

PHP Code for Sending HTML Email

<?php
// from email
$from = 'christmascontest@gmail.com'; // change this
// to email
$to = 'sally@somedomain.com, justin@somedomain.com, parker@somedomain.com'; // change this
// subject
$subject = 'Christmas Contest Announcement';

// html message
$htmlmsg = '<html>
    <head>
        <title>Christmas Contest Winners</title>
    </head>
    <body>
        <h1>Hi! We are glad to announce the Christmas contest winners...</h1>
        <table>
            <tr style="background-color: #EEE;">
                <th width="25%">#</th>
                <th width="35%">Ticket No.</th>
                <th>Name</th>
            </tr>
            <tr>
                <td>#1</td>
                <td>P646MLDO808K</td>
                <td>Sally</td>
            </tr>
            <tr style="background-color: #EEE;">
                <td>#2</td>
                <td>DFJ859LV9D5U</td>
                <td>Parker</td>
            </tr>
            <tr>
                <td>#3</td>
                <td>AU30HI8IHL96</td>
                <td>Justin</td>
            </tr>
        </table>
    </body>
</html>';

// set content type header for html email
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

// set additional headers
$headers .= 'From: Christmas Contest <christmascontest@gmail.com>' . "\r\n";
$headers .= 'Cc: contestadmin@gmail.com' . "\r\n";

// send email
if (mail($to, $subject, $htmlmsg, $headers))
    echo "Email sent successfully!";
else
    echo "Error sending email! Please try again later...";
?>

Change $from to your gmail-id and $to variable to the recipients email-id.

Plus the code includes content type header which is a must for sending html emails and additional headers should be appended with CRLF.

Note: If you have enabled two-way authentication for Google account then please disable it for this code to work.

That's all about sending html email in php via smtp server.

Read Also:

How to Disable Mouse Right Click using jQuery

On 4/02/2018 Be the first to comment!

Content theft is a serious issue faced by many website / blog owners. This can be limited to a certain level by disabling right click on websites. Disabling mouse right-click will prevent the context menu from appearing, there by preventing the page contents from being copied. Although it is not recommended as the best practice, it is certainly feasible.

It is very easy to disable the right click on your site using jquery. You can do it at page level or element level. You have to capture and cancel the event inside the event handler. We will see how to do it.

jquery disable mouse right click cut copy paste

jQuery - Disable Right Click Context Menu:

You can avoid copying the contents of your website in two ways. One is to disable the right-click context menu altogether and the other is to simply disable the cut, copy and paste operations.

1) To disable the right-click event on the entire web page, use this script,

<script type="text/javascript">
$(document).ready(function(){
    $(this).on('contextmenu', function(e){
        e.preventDefault();
    });
});
</script>

In the above script, the method on() attaches the 'contextmenu' event handler to the document. And the preventDefault() method prevents the default action of the element from happening; here it stops the context menu from showing up.

2) To disable context-menu on mouse right click only on part of the web page, use the element id, class or the element itself.

<script type="text/javascript">
$(document).ready(function(){
    $('#id').on('contextmenu', function(e){
        e.preventDefault();
    });
});
</script>

3) To disable right click context menu on the whole page but on the editable element like textarea, use this,

<script type="text/javascript">
$(document).ready(function(){
    $(this).on('contextmenu', function(e){
        if(e.target.nodeName != "TEXTAREA"){
            e.preventDefault();
        }
    });
});
</script>

Disable Cut, Copy & Paste on Webpage:

The first method will only stop users from copy pasting the contents using mouse. But they can still fire keyboard shortcuts such as CTRL+X (cut), CTRL+C (copy), CTRL+V (paste).

1) To disable just the cut, copy and paste features on your web page, use this,

<script type="text/javascript">
$(document).ready(function(){
    $(this).on('cut copy paste', function(e){
        return false;
    });
});
</script>

2) To disable cut, copy and paste operations on specific page elements, use this,

<script type="text/javascript">
$(document).ready(function(){
    $('#code').on('cut copy paste', function(e){
        return false;
    });
});
</script>
Read Also:

That's a pretty nifty solution for disabling right click on the mouse. In jquery you can use both bind() and on() methods to attach the event handler to an element. Since 'bind' is deprecated from v3.0, use 'on' from here on. I hope this tutorial is useful for you. Please share it on your social circle if you like it.

How to Add Images to Dropdown List using jQuery

On 3/30/2018 Be the first to comment!

Hi! In this post, let's see how to add images to dropdown list using jquery. I had a form with a drop-down element for the list of countries and wanted to insert the corresponding country flag before each country name. But HTML does not support the addition of elements to select box. Then I found some CSS hack but this method is not compatible with all browsers. Finally, I decided to go with java script and found a fairly neat solution.

Actually, it is a jquery plugin called 'select2'. It includes the autocomplete feature to dropdown list, but also allows you to add icons to those select options. Below, I'll show you how to use the select2 add-on to insert country flags before the country names in a drop-down list.

jquery add images to dropdown list

jQuery - Adding Images to the Dropdown List:

STEP-1) First load the 'jQuery' and 'Select2' libraries on the Web page. You need to add both 'css' and 'js' files of the plugin.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

STEP-2) Next, load the library for country flag icons. This will help us to display images of flags of all countries.

<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/css/flag-icon.min.css" rel="stylesheet" />

STEP-3) Now create an empty drop down element to add the country names and flags.

<select id="countries">
    <option></option>
</select>

STEP-4) Finally the JavaScript. This is the main part of the task. Here we have to create a JS array that contains all the country names and their IDs and pass it to the drop-down element that we created in the previous step.

<script type="text/javascript">
$(document).ready(function() {
    var options = [
        { id: 'AF', text: 'Afghanistan'},{ id: 'AX', text: 'Aland Islands'},{ id: 'AL', text: 'Albania'},{ id: 'DZ', text: 'Algeria'},{ id: 'AS', text: 'American Samoa'},
        { id: 'AD', text: 'Andorra'},{ id: 'AO', text: 'Angola'},
        { id: 'AI', text: 'Anguilla'},{ id: 'AQ', text: 'Antarctica'},{ id: 'AG', text: 'Antigua And Barbuda'},
        { id: 'AR', text: 'Argentina'},{ id: 'AM', text: 'Armenia'},{ id: 'AW', text: 'Aruba'},
        { id: 'AU', text: 'Australia'},{ id: 'AT', text: 'Austria'},{ id: 'AZ', text: 'Azerbaijan'},{ id: 'BS', text: 'Bahamas'},{ id: 'BH', text: 'Bahrain'},{ id: 'BD', text: 'Bangladesh'},{ id: 'BB', text: 'Barbados'},{ id: 'BY', text: 'Belarus'},{ id: 'BE', text: 'Belgium'},
        { id: 'BZ', text: 'Belize'},{ id: 'BJ', text: 'Benin'},
        { id: 'BM', text: 'Bermuda'},{ id: 'BT', text: 'Bhutan'},
        { id: 'BO', text: 'Bolivia'},{ id: 'BA', text: 'Bosnia And Herzegovina'},{ id: 'BW', text: 'Botswana'},    { id: 'BV', text: 'Bouvet Island'},{ id: 'BR', text: 'Brazil'},
        { id: 'IO', text: 'British Indian Ocean Territory'},{ id: 'BN', text: 'Brunei Darussalam'},{ id: 'BG', text: 'Bulgaria'},{ id: 'BF', text: 'Burkina Faso'},{ id: 'BI', text: 'Burundi'},{ id: 'KH', text: 'Cambodia'},{ id: 'CM', text: 'Cameroon'},{ id: 'CA', text: 'Canada'},
        { id: 'CV', text: 'Cape Verde'},{ id: 'KY', text: 'Cayman Islands'},{ id: 'CF', text: 'Central African Republic'},{ id: 'TD', text: 'Chad'},{ id: 'CL', text: 'Chile'},{ id: 'CN', text: 'China'},{ id: 'CX', text: 'Christmas Island'},{ id: 'CC', text: 'Cocos (Keeling) Islands'},{ id: 'CO', text: 'Colombia'},{ id: 'KM', text: 'Comoros'},{ id: 'CG', text: 'Congo'},{ id: 'CD', text: 'Congo, Democratic Republic Of'},{ id: 'CK', text: 'Cook Islands'},{ id: 'CR', text: 'Costa Rica'},{ id: 'CI', text: 'Cote D\'Ivoire'},{ id: 'HR', text: 'Croatia'},
        { id: 'CU', text: 'Cuba'},{ id: 'CY', text: 'Cyprus'},
        { id: 'CZ', text: 'Czech Republic'},{ id: 'DK', text: 'Denmark'},{ id: 'DJ', text: 'Djibouti'},{ id: 'DM', text: 'Dominica'},{ id: 'DO', text: 'Dominican Republic'},
        { id: 'EC', text: 'Ecuador'},{ id: 'EG', text: 'Egypt'},
        { id: 'SV', text: 'El Salvador'},{ id: 'GQ', text: 'Equatorial Guinea'},{ id: 'ER', text: 'Eritrea'},
        { id: 'EE', text: 'Estonia'},{ id: 'ET', text: 'Ethiopia'},{ id: 'FK', text: 'Falkland Islands (Malvinas)'},
        { id: 'FO', text: 'Faroe Islands'},{ id: 'FJ', text: 'Fiji'},{ id: 'FI', text: 'Finland'},{ id: 'FR', text: 'France'},{ id: 'GF', text: 'French Guiana'},{ id: 'PF', text: 'French Polynesia'},{ id: 'TF', text: 'French Southern Territories'},{ id: 'GA', text: 'Gabon'},{ id: 'GM', text: 'Gambia'},{ id: 'GE', text: 'Georgia'},{ id: 'DE', text: 'Germany'},{ id: 'GH', text: 'Ghana'},{ id: 'GI', text: 'Gibraltar'},{ id: 'GR', text: 'Greece'},
        { id: 'GL', text: 'Greenland'},{ id: 'GD', text: 'Grenada'},{ id: 'GP', text: 'Guadeloupe'},{ id: 'GU', text: 'Guam'},{ id: 'GT', text: 'Guatemala'},{ id: 'GG', text: 'Guernsey'},{ id: 'GN', text: 'Guinea'},{ id: 'GW', text: 'Guinea-Bissau'},{ id: 'GY', text: 'Guyana'},
        { id: 'HT', text: 'Haiti'},{ id: 'HM', text: 'Heard Island & Mcdonald Islands'},{ id: 'VA', text: 'Holy See (Vatican City State)'},{ id: 'HN', text: 'Honduras'},
        { id: 'HK', text: 'Hong Kong'},{ id: 'HU', text: 'Hungary'},{ id: 'IS', text: 'Iceland'},
        { id: 'IN', text: 'India'},{ id: 'ID', text: 'Indonesia'},
        { id: 'IR', text: 'Iran, Islamic Republic Of'},{ id: 'IQ', text: 'Iraq'},{ id: 'IE', text: 'Ireland'},{ id: 'IM', text: 'Isle Of Man'},{ id: 'IL', text: 'Israel'},
        { id: 'IT', text: 'Italy'},{ id: 'JM', text: 'Jamaica'},
        { id: 'JP', text: 'Japan'},{ id: 'JE', text: 'Jersey'},
        { id: 'JO', text: 'Jordan'},{ id: 'KZ', text: 'Kazakhstan'},{ id: 'KE', text: 'Kenya'},{ id: 'KI', text: 'Kiribati'},{ id: 'KR', text: 'Korea'},{ id: 'KW', text: 'Kuwait'},{ id: 'KG', text: 'Kyrgyzstan'},{ id: 'LA', text: 'Lao People\'s Democratic Republic'},{ id: 'LV', text: 'Latvia'},{ id: 'LB', text: 'Lebanon'},{ id: 'LS', text: 'Lesotho'},{ id: 'LR', text: 'Liberia'},{ id: 'LY', text: 'Libyan Arab Jamahiriya'},{ id: 'LI', text: 'Liechtenstein'},{ id: 'LT', text: 'Lithuania'},{ id: 'LU', text: 'Luxembourg'},{ id: 'MO', text: 'Macao'},
        { id: 'MK', text: 'Macedonia'},{ id: 'MG', text: 'Madagascar'},{ id: 'MW', text: 'Malawi'},{ id: 'MY', text: 'Malaysia'},{ id: 'MV', text: 'Maldives'},
        { id: 'ML', text: 'Mali'},{ id: 'MT', text: 'Malta'},
        { id: 'MH', text: 'Marshall Islands'},{ id: 'MQ', text: 'Martinique'},{ id: 'MR', text: 'Mauritania'},{ id: 'MU', text: 'Mauritius'},{ id: 'YT', text: 'Mayotte'},
        { id: 'MX', text: 'Mexico'},{ id: 'FM', text: 'Micronesia, Federated States Of'},{ id: 'MD', text: 'Moldova'},{ id: 'MC', text: 'Monaco'},{ id: 'MN', text: 'Mongolia'},{ id: 'ME', text: 'Montenegro'},{ id: 'MS', text: 'Montserrat'},{ id: 'MA', text: 'Morocco'},{ id: 'MZ', text: 'Mozambique'},{ id: 'MM', text: 'Myanmar'},
        { id: 'NA', text: 'Namibia'},{ id: 'NR', text: 'Nauru'},
        { id: 'NP', text: 'Nepal'},{ id: 'NL', text: 'Netherlands'},{ id: 'AN', text: 'Netherlands Antilles'},
        { id: 'NC', text: 'New Caledonia'},{ id: 'NZ', text: 'New Zealand'},{ id: 'NI', text: 'Nicaragua'},{ id: 'NE', text: 'Niger'},{ id: 'NG', text: 'Nigeria'},{ id: 'NU', text: 'Niue'},{ id: 'NF', text: 'Norfolk Island'},{ id: 'MP', text: 'Northern Mariana Islands'},{ id: 'NO', text: 'Norway'},{ id: 'OM', text: 'Oman'},{ id: 'PK', text: 'Pakistan'},{ id: 'PW', text: 'Palau'},{ id: 'PS', text: 'Palestinian Territory, Occupied'},{ id: 'PA', text: 'Panama'},{ id: 'PG', text: 'Papua New Guinea'},{ id: 'PY', text: 'Paraguay'},{ id: 'PE', text: 'Peru'},
        { id: 'PH', text: 'Philippines'},{ id: 'PN', text: 'Pitcairn'},{ id: 'PL', text: 'Poland'},{ id: 'PT', text: 'Portugal'},{ id: 'PR', text: 'Puerto Rico'},{ id: 'QA', text: 'Qatar'},{ id: 'RE', text: 'Reunion'},
        { id: 'RO', text: 'Romania'},{ id: 'RU', text: 'Russian Federation'},{ id: 'RW', text: 'Rwanda'},{ id: 'BL', text: 'Saint Barthelemy'},{ id: 'SH', text: 'Saint Helena'},
        { id: 'KN', text: 'Saint Kitts And Nevis'},{ id: 'LC', text: 'Saint Lucia'},{ id: 'MF', text: 'Saint Martin'},
        { id: 'PM', text: 'Saint Pierre And Miquelon'},{ id: 'VC', text: 'Saint Vincent And Grenadines'},{ id: 'WS', text: 'Samoa'},{ id: 'SM', text: 'San Marino'},{ id: 'ST', text: 'Sao Tome And Principe'},{ id: 'SA', text: 'Saudi Arabia'},{ id: 'SN', text: 'Senegal'},{ id: 'RS', text: 'Serbia'},{ id: 'SC', text: 'Seychelles'},{ id: 'SL', text: 'Sierra Leone'},{ id: 'SG', text: 'Singapore'},{ id: 'SK', text: 'Slovakia'},{ id: 'SI', text: 'Slovenia'},
        { id: 'SB', text: 'Solomon Islands'},{ id: 'SO', text: 'Somalia'},{ id: 'ZA', text: 'South Africa'},{ id: 'GS', text: 'South Georgia And Sandwich Isl.'},{ id: 'ES', text: 'Spain'},{ id: 'LK', text: 'Sri Lanka'},
        { id: 'SD', text: 'Sudan'},{ id: 'SR', text: 'Suriname'},
        { id: 'SJ', text: 'Svalbard And Jan Mayen'},{ id: 'SZ', text: 'Swaziland'},{ id: 'SE', text: 'Sweden'},{ id: 'CH', text: 'Switzerland'},{ id: 'SY', text: 'Syrian Arab Republic'},{ id: 'TW', text: 'Taiwan'},{ id: 'TJ', text: 'Tajikistan'},{ id: 'TZ', text: 'Tanzania'},
        { id: 'TH', text: 'Thailand'},{ id: 'TL', text: 'Timor-Leste'},{ id: 'TG', text: 'Togo'},{ id: 'TK', text: 'Tokelau'},{ id: 'TO', text: 'Tonga'},{ id: 'TT', text: 'Trinidad And Tobago'},{ id: 'TN', text: 'Tunisia'},
        { id: 'TR', text: 'Turkey'},{ id: 'TM', text: 'Turkmenistan'},{ id: 'TC', text: 'Turks And Caicos Islands'},{ id: 'TV', text: 'Tuvalu'},{ id: 'UG', text: 'Uganda'},{ id: 'UA', text: 'Ukraine'},{ id: 'AE', text: 'United Arab Emirates'},{ id: 'GB', text: 'United Kingdom'},{ id: 'US', text: 'United States'},{ id: 'UM', text: 'United States Outlying Islands'},{ id: 'UY', text: 'Uruguay'},{ id: 'UZ', text: 'Uzbekistan'},{ id: 'VU', text: 'Vanuatu'},{ id: 'VE', text: 'Venezuela'},{ id: 'VN', text: 'Viet Nam'},{ id: 'VG', text: 'Virgin Islands, British'},{ id: 'VI', text: 'Virgin Islands, U.S.'},{ id: 'WF', text: 'Wallis And Futuna'},{ id: 'EH', text: 'Western Sahara'},{ id: 'YE', text: 'Yemen'},
        { id: 'ZM', text: 'Zambia'},{ id: 'ZW', text: 'Zimbabwe'}
    ];
    $('#countries').select2({
        placeholder: '-Select Country-',
        templateResult: formatCountry,
        data: options
    });
    
    function formatCountry(country){
        if (!country.id) {
            return country.text;
        }
        var $country = $(
            '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' + '<span style="margin-left:10px;">'+ country.text+'</span>'
        );
        return $country;
    };
});
</script>

In the above script, the select2() method will simply replace the plain dropdown with a more customizable one. We also have to set the formatting function to the templateResult option. This will execute the function for each option in the drop down and will add a country flag image to it.

Run the script and you will see a nice dropdown that shows the country names with their flags. It also includes an amazing search box which will autosuggest the names of countries when you start typing.

insert country flag images before country names select2
Read Also:

Likewise, you can add images to the select box using the jquery select2 plugin. It's a nifty add-on that gives you more control over the element which you never get with HTML. I hope this tutorial is useful for you. Please share it on social media if you like it.

Dynamic Treeview Menu using PHP, MySQL and AJAX Example

On 3/26/2018 Be the first to comment!

How to Create Dynamic Treeview Menu using PHP, MySQL and AJAX? Most modern websites use tree view to display the dynamic sidebar menu for easy navigation. In case you don't know, a Treeview is a hierarchical representation of elements in a tree-like structure. You can go for jquery solution in this context, but I would recommend 'Bootstrap Treeview' plug-in if you use the bootstrap framework to build your websites.

The plug-in uses JSON dataset to create a hierarchical tree structure. I have already discussed the creation of static treeview menu using bootstrap treeview. But you can also generate a dynamic tree where you pull off the data elements stored in the database. In this tutorial I'm going to show you about creating dynamic treeview using php, mysql, ajax and bootstrap.

bootstrap dynamic treeview example

How to Create Dymanic Treeview in PHP & MySQL?

For the demo, I'm going to load all the required libraries via CDN. So there's no need to download them to your web server.

Here are the simple steps to build a dynamic tree view structure.

STEP-1) First create the mysql database required for the example. I would suggest you follow the same schema given below to maintain the hierarchy structure.

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE `tbl_categories` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(50) NOT NULL,
  `parent_id` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=18;

INSERT INTO `tbl_categories` (`id`, `item_name`, `parent_id`) VALUES
(1, 'Electronics', 0),
(2, 'Televisions', 1),
(3, 'Tube', 2),
(4, 'LCD', 2),
(5, 'Plasma', 2),
(6, 'Computers and Laptops', 1),
(7, 'Desktops', 6),
(8, 'Laptops', 6),
(9, 'Netbooks', 6),
(10, 'Tablets', 6),
(11, 'Android', 10),
(12, 'iPad', 10),
(13, 'Mobile Phones', 1),
(14, 'Basic Cell Phones', 13),
(15, 'Smartphones', 13),
(16, 'Android Phones', 15),
(17, 'iPhone', 15);

STEP-2) Next create a php script to be executed by ajax call. This will fetch the menu data from the 'tbl_categories' table, create hierarchical tree structure and return it as JSON data.

fetch_categories.php

<?php
$db = mysqli_connect('localhost', 'mysql_username', 'mysql_password', 'my_demo');
$sql = 'select id, item_name as name, item_name as text, parent_id from tbl_categories';
$result = mysqli_query($db, $sql);

$tree_data = mysqli_fetch_all($result, MYSQLI_ASSOC);

foreach($tree_data as $k => &$v){
    $tmp_data[$v['id']] = &$v;
}

foreach($tree_data as $k => &$v){
    if($v['parent_id'] && isset($tmp_data[$v['parent_id']])){
        $tmp_data[$v['parent_id']]['nodes'][] = &$v;
    }
}

foreach($tree_data as $k => &$v){
    if($v['parent_id'] && isset($tmp_data[$v['parent_id']])){
        unset($tree_data[$k]);
    }
}

echo json_encode($tree_data);
?>

STEP-3) Finally, create an HTML file and add placeholder to show the tree view. Here you have to load all the required libraries such as bootstrap, jquery and bootstrap treeview libraries.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>PHP and MySQl Dynamic Treeview Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-4">
            <h3 class="text-center bg-primary">Dynamic Treeview Example</h3>
                <div id="myTree"></div>
            </div>

            <div class="col-sm-8">
                <!-- here goes other page contents -->
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: 'fetch_categories.php',
            method: 'GET',
            dataType: 'json',
            success: function(data){
                $('#myTree').treeview({data: data});
            }
        });
    });
    </script>
</body>
</html>

In the success function of the ajax() call, we have invoked the treeview() method of the 'bootstrap-treeview' library to display the tree structure on the corresponding placeholder.

When you run 'index.html' a tree menu similar to this one will appear,

ajax dynamic treeview php mysql example
Read Also:

Similarly, you can create treeview dynamically using php, mysql and ajax. You can also add icons, check boxes and filters to the nodes of the tree menu. Check the documentation to learn more about it. I hope this tutorial is useful for you. Please share it on social media if you like it.

Contact Form

Name

Email *

Message *