Save Codeigniter config data in MySql database

In this tutorial, I want to show you how to save the codeigniter config data in mysql database. It means we will save config data in mysql and can grab these data when we need to use in our project and can also edit form our site dynamically.

Step 1: Configuration

For application/config/routes.php file

$route['default_controller'] = "home";

For application/config/config.php file

$config['base_url'] = 'http://localhost/ci_config/';

and

$config['enable_hooks'] = TRUE;

For application/config/autoload.php file

$autoload['libraries'] = array('database');

and

$autoload['helper'] = array('url','form');

and

$autoload['model'] = array('Siteconfig');

For application/config/database.php file

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'ciconfig';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';

For application/config/hooks.php file

You need to add below code to your hooks.php file.

$hook['post_controller_constructor'] = array(
         'class'    => '',
         'function' => 'load_config',
         'filename' => 'my_config.php',
         'filepath' => 'hooks'
         );

You can learn more about hooks in the CI documentation here.

Setp 2: Creating Hooks file

Open new document in your favourite editor and type below code and save as application/hooks/my_config.php

   //Loads configuration from database into global CI config   function load_config()   {    $CI =& get_instance();    foreach($CI->Siteconfig->get_all()->result() as $site_config)
   {
    $CI->config->set_item($site_config->key,$site_config->value);
   }
  }

We grab the config data from our database by using Siteconfig model. And set the data to global CI config. So we need to create Siteconfig model in our model folder.

Step 3:Creating database

Create a database from your MySql admin as ciconfig and run below code in your mysql tool.

CREATE TABLE IF NOT EXISTS `config_data` (
  `key` varchar(255) NOT NULL,
  `value` varchar(255) NOT NULL,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `config_data`
--

INSERT INTO `config_data` (`key`, `value`) VALUES
('sitedescription', 'Tutorials for Web development and design'),
('sitename', 'TutsforWeb');

Step 4:Creating Siteconfig model

Open new document in your favourite editor and type below code and save as application/models/siteconfig.php

class Siteconfig extends CI_Model {  public function __construct()  {   parent::__construct();  }  public function get_all()  {   return $this->db->get('config_data');
 }
 public function update_config($data)
 {
  $success = true;
  foreach($data as $key=>$value)
  {
   if(!$this->save($key,$value))
   {
    $success=false;
    break;  
   }
  }
  return $success;
 }
 public function save($key,$value)
 {
  $config_data=array(
    'key'=>$key,
    'value'=>$value
    );
  $this->db->where('key', $key);
  return $this->db->update('config_data',$config_data); 
 }
}

get_all() function is used in our my_config hooks file to grab all data from our database.

update_config() function is used to update our config data when the form is submitted from config view file.
save() function is called form the update_config() function to update one by one.

Step 5:Creating home Controller

Open new document in your favourite editor and type below code and save as application/controllers/home.php


if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home extends CI_Controller {   public function index()   {    $this->load->view('home');
  }
  public function config()
  {
   $this->load->view('config');
  }
  public function update()
  {
   $update_data=array(
      'sitename'=>$this->input->post('sitename'),
      'sitedescription'=>$this->input->post('sitedescription')
      );
   $success = $this->Siteconfig->update_config($update_data);
   if($success) redirect("/home/index");
  }
}

Step 6:Creating view files

Open new document in your favourite editor and type below code and save as application/views/home.php

  


  
   config->item('sitename'); ?>
  

  

config->item('sitename'); ?>

config->item('sitedescription'); ?>

<a href="index.php/home/config">Site Config

As you see above code, we can use our config data by using this script

echo $this->config->item('sitename');

We need to create the config view file to edit config data dynamically. Open new document in your favourite editor and type below code and save as application/views/config.php

  
    echo $this->config->item('sitename');

echo form_open(“home/update”);
Site Name :
<input id="sitename" name="sitename" size="40" type="text" value="config->item(‘sitename’); ?>” />

Site Description :
<input id="sitedescription" name="sitedescription" size="40" type="text" value="config->item(‘sitedescription’); ?>” />


If you click the Site Config from our home page, this page will be loaded and you can edit and update our config data.

Happy Coding…..

Advertisements

Stripe Payment Integration & Development in Codeigniter

This blog gives an overview on integration of stripe payment service in Codeigniter.

There are two types of payment services we can integrate using stripe.

  • Recurring Payment.
  • One Time Payment.

First step is to create a stripe account. Use the below link to create an account.

https://dashboard.stripe.com/register

Once registered, confirm your email address using the activation link received in email. It will redirect you to a login page of stripe website. After login, you will be redirected to dashboard.

Recurring Payment

For this, we need to create a new subscription plan which will be used for recurring payment. To create a plan, click on Subscriptions from left menu -> Plans -> New. It will open a popup to create new plan as shown below.

CreateNewPlan

We need to provide details for the below fields.

ID: Used for recurring payment which can be numeric or alpha numeric.

Name: Name of your subscription plan.

Currency: Select currency in which we want to accept payments.

Amount: Amount for the subscription.

Interval: Select subscription period. There are seven options available like daily, monthly, yearly, weekly, every 3 months, every 6 months and custom. In custom, we can set our own subscription period by entering number and selecting period from drop down like month(s), week(s) or day(s).

Trial period days: This field is optional and it is used if we want to give subscription as a trial for mentioned day(s).

Statement description: A description of the payment plan which optional and appear on statement.

When someone pays for the subscription or does a recurring payment, it is mandatory to create a customer. We can create customer through a php code.

 

$card_data = array(

            ‘number’ => $this->input->post(‘card_number’),

            ‘cvc’ => $this->input->post(‘cvv’),

            ‘exp_month’ => $this->input->post(‘exp_month’),

            ‘exp_year’ => $this->input->post(‘exp_year’),

            ‘name’ => $this->input->post(’email’),

 );

 $dollars = str_replace(‘$’, ”, $this->input->post(‘amount’));

$cents = number_format((float)$dollars*100., 0, ‘.’, ”);   

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cent));

$stripeToken = $tokenArray->id;

$card = $stripeToken;

$email = $this->input->post(’email’);

$desc = $this->input->post(‘service_name’);

$plan = $this->input->post(‘plan_name’);

$customerCreateArray = json_decode($this->stripe->customer_create( $card, $email, $desc, $plan));

$customer_id = $customerCreateArray->id; //return inserted customer id

 

How to integrate stripe payment gateway in codeigniter?

We need to create a basic view file which will accept the required data from the user like card number, card expiry month, card expiry year, card CVV number etc.

We need to mention controllerMethodName in the action of the form as shown below.

<form action=”controllerMethodName” method=”post”>

         

                  

Stripe Payment

                   $ 11.50

                  

                            

                                     

Card Number

                                     

                                     

                            

                            

                                     

Email Address

                                     

                            

                  

                            

                                     

Exp. Month

                                     

                            

                            

                                     

Exp. Year

                                     

                            

                            

                                     

CVV

                                     

                            

                            

                                      Pay Now

                            

                   </div>

          </div> 

</form>

To integrate stripe payment gateway, we need two files. One is the library file and another is the configuration file. Both these files can be downloaded from the below URL.

https://github.com/chrismackie28/php-stripe

After downloading the zip file from the above URL, we will get two files: one is README.md and another is Stripe.php

We need to create one configuration file and put it in codeigniter’s application/config/stripe.php and put the following configurations.

// Configuration options

$config[‘stripe_key_test_public’]         = ”;

$config[‘stripe_key_test_secret’]         = ”;

$config[‘stripe_key_live_public’]         = ”;

$config[‘stripe_key_live_secret’]         = ”;

$config[‘stripe_test_mode’]               = TRUE;

$stripe = new Stripe( $config ); // Create the library object

Copy the above code and save it as stripe.php in config folder so the path of this file will be like: <PROJECT_FOLDER>/application/config/stripe.php

Stripe.php file will be placed in our codeigniter’s application/libraries folder, so the path of the Stripe.php file is like: <PROJECT_FOLDER>/application/libraries/Stripe.php

The basic functions are defined in the Stripe.php.

Steps to integrate stripe in Codeigniter

Include library file

$this->load->library(‘stripe’);

Recurring Payment Code

Below piece of code is used to create a card token

$card_data = array(

          ‘number’ => $this->input->post(‘card_number’),

          ‘cvc’ => $this->input->post(‘cvv’),

          ‘exp_month’ => $this->input->post(‘exp_month’),

          ‘exp_year’ => $this->input->post(‘exp_year’),

          ‘name’ => $this->input->post(’email’),

);

$dollars = $this->input->post(‘amount’);

$cents = number_format((float)$dollars*100., 0, ‘.’, ”); // convert dollar to cent

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cents));

$stripeToken = $tokenArray->id;

NOTE: We need to convert the amount into cents because stripe accept payment in cents. (e.g. $2.5 = 250cents)

We need to create a customer using below piece of code.

$card = $stripeToken;

$email = $this->input->post(’email’);

$desc = $this->input->post(‘description’);

$plan = $this->input->post(‘plan_id’);

$customerCreateArray = json_decode($this->stripe->customer_create( $card, $email, $desc, $plan));

$customer_id = $customerCreateArray->id;

$amount =  $cents;

$card = $card_data;

$desc = $this->input->post(‘description’);

$payWithStripe = json_Decode($this->stripe->charge_card($amount, $card, $desc));

We need to store the data into database and get the transaction id.

$transaction_id = $payWithStripe->id;

To cancel the subscription, use the below code.

$customer_id = $this->input->post(‘customer_id’);

$result = json_decode($this->stripe->customer_unsubscribe($customer_id,true));

$cancel_date = $result->current_period_end;

In the above function if we pass true then the subscription will be cancel at the end of the subscription period and if we pass it false then subscription will cancel immediately.

One Time Payment

Code is same as the recurring payment code. The only change is that it is not necessary to create a customer for onetime payment in stripe.

One Time Payment Code

Below piece of code is used to create a card token

$card_data = array(

          ‘number’ => $this->input->post(‘card_number’),

          ‘cvc’ => $this->input->post(‘cvv’),

          ‘exp_month’ => $this->input->post(‘exp_month’),

          ‘exp_year’ => $this->input->post(‘exp_year’),

          ‘name’ => $this->input->post(’email’),

);

$dollars = $this->input->post(‘amount’);

$cents = number_format((float)$dollars*100., 0, ‘.’, ”); // convert dollar to cent

$tokenArray = json_decode($this->stripe->card_token_create($card_data,$cents));

$stripeToken = $tokenArray->id;

$amount =  $cents;

$card = $card_data;

$desc = $this->input->post(‘description’);

$payWithStripe = json_Decode($this->stripe->charge_card($amount, $card, $desc));

 

We need to store the data into database and get the transaction id.

 

$transaction_id = $payWithStripe->id;

How to zip, save and download a file in codeigniter

In this article we are going to see how to zip, save, download a file in codeigniter PHP framework. codeigniter is a very popular PHP framework.  Codeigniter framework you can do many tasks very easily. Compressing and downloading or saving can be done very easily.

Zip Encoding Class

Zip class is used to create and download archives.  In controller you can initialize the zip class using

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

After loading the library we can use the zip object.

$this->zip

 Zip, Save and Download a file

The code snippet below shows how to create a zip file, save it and download it.

$filename = 'example.txt';

$filedata = 'This is an example file. Codeigniter zip class is used to zip, save and download the file';

$this->zip->add_data($filename, $filedata);

//Write the zip file to a folder on server with name. "example_backup.zip"

$this->zip->archive('/images/example_backup.zip');

//Download the file to system. Name it "my_backup.zip"
$this->zip->download('example_backup.zip');

Adding Controller in CodeIgniter

So if you want to zip, save, download a file in codeigniter then you have to do following

1. In Controller folder, Add a controller file and name it as, “Zip.php”2. Add a folder named “zippedfiles” in root folder.

3. Add the code below to the Zip.php file. 4. Run the code, a zip file is created and downloaded to your computer

Codeigniter controller code

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

  class Zip extends CI_Controller {

        public function __construct()
        {
            parent::__construct();
            $this->load->library('zip');
        }

        public function index()
        {
        
            $filename = 'example.txt';
            $filedata = 'This is an example file. Codeigniter zip class is 
                         used to zip, save and download the file';

            $this->zip->add_data($filename, $filedata); 
            
            //Create zip file on server with name."example_backup.zip"
            $this->zip->archive('/zippedfiles/example_backup.zip');  

            //Download the file to your system. It will be named "example_backup.zip"
            $this->zip->download('example_backup.zip');
        }
    }

Code Explanation

In code above We have created a class named Zip that extends CI_Controller. Inside constructor, that runs each time when a class object is created.  After calling parent constructor, we load zip library.

Inside index action we create a variable name $filename and a $filedata with content.

add_data method

$this->zip->add_data($filename, $filedata);

Zip object’s add_data method is called with $filename and $filedata params.

archive method

$this->zip->archive('/zippedfiles/example_backup.zip');  

The code above, archive method of zip object saves file to a specified path.

download method

$this->zip->download('example_backup.zip');

Finally the download method of zip class object downloads file to user’s computer.  The code above can be used in any of your project to zip and download zip archives.

 

source: https://programmerblog.net/

Create Multiple Database Connections In CodeIgniter Applications

In real world CodeIgniter projects, developers need to work with multiple databases at the same time. This presents a unique challenge to developers. Since this is a common enough problem, CodeIgniter offers a simple solution for it.

In order to use multiple database connections in your CodeIgniter project, you just need to create multiple configuration arrays that simplify working with multiple databases.

The Default Configuration Array

Following is the structure of the default Codeigniter database configuration array:

So in order to create another database connection, you should create another configuration array. This array has to follow the same structure. Here is an example of the array:

Connect to the Right Database

At this point, you have two databases in your sample project. To connect to a specific database, you must specify the database name. Here is the proper syntax:

Now if you need to work with the second database, you have to send the connection to a variable that is usable in your model:

Close the Connections

CodeIgniter does close the database connections after it determines that the code no longer need the connection. However, as a good practice, developers should close the connections explicitly. Here is how to take care of the issue:

Conclusion

In this article, I have discussed the problem and the solution to using multiple database connections in CodeIgniter projects. If you need help with implementing the idea in your projects, do leave a comment below and I will get back to you.

By Owais Alam

Pass Data From One Function To Another In Same Codeigniter Controller

A controller often comprises of several functions and often the module’s logic demands passing data between the various functions of the Controller. This is a common enough scenario in many Codeigniter projects. In this tutorial, I will demonstrate how you could pass data between two functions within the same Controller in CodeIgniter. In addition, I will show this data in the View.

pass data between functions in CodeIgniter

Here is what the Model looks like:

Model

The Controller is as follows:

Controller

The following View shows the data that has been passed between the functions of the Controller.

View

Conclusion

In this tutorial, I have discussed how to pass data from one function to another in a Controller. You could easily extend this idea within your Codeigniter projects. If you need help, do leave a comment below.

 

 

By Shahroze Nawaz  September 27, 2017

 

 

 

 

How to route the URI with parameters to a method in codeigniter?

Solution 1

n CI 3.x the (:any) parameter matches only a single URI segment. So for example:

$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';

will match exactly two segments and pass them appropriately. If you want to match 1 or 2 you can do this (in order):

$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';
$route['method/(:any)'] = 'controller/method/$1';

You can pass multiple segments with the (.+) parameter like this:

$route['method/(.+)'] = 'controller/method/$1';

In that case the $1 will contain everything past method/. In general I think its discouraged to use this since you should know what is being passed and handle it appropriately but there are times (.+) comes in handy. For example if you don’t know how many parameters are being passed this will allow you to capture all of them. Also remember, you can set default parameters in your methods like this:

public function method($param=''){}

So that if nothing is passed, you still have a valid value.

You can also pass to your index method like this:

$route['method/(:any)/(:any)'] = 'controller/method/index/$1/$2';
$route['method/(:any)'] = 'controller/method/index/$1';

Obviously these are just examples. You can also include folders and more complex routing but that should get you started.

 

 

Solution 2

 

Setting up custom routes for HMVC Easy here are some examples below. You can use sametechneique for CI3 Make sure you choose right version from here https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/downloads go to branches and choose your version The Default is for CI-2

$route['default_controller'] = 'catalog/common/welcome/index';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

// Common
$route['admin'] = "admin/common/login/index";
$route['admin/dashboard'] = "admin/common/dashboard/index";
$route['admin/logout'] = "admin/common/logout/index";
$route['admin/register'] = "admin/common/register/index";

// Users
$route['admin/users/user_edit/(:any)'] = "admin/user/users/user_edit/$1";
$route['admin/users/user_password/(:any)'] = "admin/user/users/user_password/$1";
$route['admin/users/user_key/(:any)'] = "admin/user/users/user_key/$1";

For Example:

admin will be module name.

application modules / admin <-- Admin Module Name

application / modules / admin / controllers / common <-- Sub folder
application / modules / admin / controllers / users <-- Sub folder

Please watch this great tutorial for beginners on HMVC https://www.youtube.com/watch?v=8fy8E_C5_qQ

You can also download Htaccess from here http://www.insiderclub.org/downloads you may need to join for free to download David’s Insider Club suitable for codeigniter.

DataTables – Server-side Processing in Codeigniter using Ajax

From this tutorial we have started learning one new topics in Codeigniter tutorial. In this topics we will discuss how can we make crud system by using Ajax with Codeigniter framework. In this system we will use DataTables Jquery plugin for display data in tabular format and we will also use Bootstrap modals for inserting and updating data. Here we will implement DataTables server side processing by using Ajax. This is the first part in which we will fetch data from Mysql table by using Ajax in Codeigniter Application and then after we will displaying that data in on web page by using DataTables jquery plugin with server side processing. In server side processing we have to write query for search, order and pagination at server side. This all things we will learn in this part. We have make simple query for all different condition like searching, ordering or even pagination and this query has been called by Ajax in codeigniter framework. So we can smoothly search table, can see data in different order or pagination which has been handle by Ajax server side processing in data tables. We can perform different operation in data table by using Ajax in Codeigniter application.

Source Code

Controllers – crud.php

<?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Crud extends CI_Controller {  
      //functions  
      function index(){  
           $data["title"] = "Codeigniter Ajax CRUD with Data Tables and Bootstrap Modals";  
           $this->load->view('crud_view', $data);  
      }  
      function fetch_user(){  
           $this->load->model("crud_model");  
           $fetch_data = $this->crud_model->make_datatables();  
           $data = array();  
           foreach($fetch_data as $row)  
           {  
                $sub_array = array();  
                $sub_array[] = '<img src="'.base_url().'upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" />';  
                $sub_array[] = $row->first_name;  
                $sub_array[] = $row->last_name;  
                $sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs">Update</button>';  
                $sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs">Delete</button>';  
                $data[] = $sub_array;  
           }  
           $output = array(  
                "draw"                    =>     intval($_POST["draw"]),  
                "recordsTotal"          =>      $this->crud_model->get_all_data(),  
                "recordsFiltered"     =>     $this->crud_model->get_filtered_data(),  
                "data"                    =>     $data  
           );  
           echo json_encode($output);  
      }  
 }  

Models – crud_model.php

 <?php  
 class Crud_model extends CI_Model  
 {  
      var $table = "users";  
      var $select_column = array("id", "first_name", "last_name", "image");  
      var $order_column = array(null, "first_name", "last_name", null, null);  
      function make_query()  
      {  
           $this->db->select($this->select_column);  
           $this->db->from($this->table);  
           if(isset($_POST["search"]["value"]))  
           {  
                $this->db->like("first_name", $_POST["search"]["value"]);  
                $this->db->or_like("last_name", $_POST["search"]["value"]);  
           }  
           if(isset($_POST["order"]))  
           {  
                $this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);  
           }  
           else  
           {  
                $this->db->order_by('id', 'DESC');  
           }  
      }  
      function make_datatables(){  
           $this->make_query();  
           if($_POST["length"] != -1)  
           {  
                $this->db->limit($_POST['length'], $_POST['start']);  
           }  
           $query = $this->db->get();  
           return $query->result();  
      }  
      function get_filtered_data(){  
           $this->make_query();  
           $query = $this->db->get();  
           return $query->num_rows();  
      }       
      function get_all_data()  
      {  
           $this->db->select("*");  
           $this->db->from($this->table);  
           return $this->db->count_all_results();  
      }  
 }  

Views – crud_view.php

<>

 <html>  
 <head>  
   <title><?php echo $title; ?></title>  
      https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js  
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
      https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js  
      https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js            
      <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  
   <style>  
           body  
           {  
                margin:0;  
                padding:0;  
                background-color:#f1f1f1;  
           }  
           .box  
           {  
                width:900px;  
                padding:20px;  
                background-color:#fff;  
                border:1px solid #ccc;  
                border-radius:5px;  
                margin-top:10px;  
           }  
      </style>  
 </head>  
 <body>  <code> 
      



Image First Name Last Name Edit Delete
</div> </code> </body> </html> $(document).ready(function(){ var dataTable = $('#user_data').DataTable({ "processing":true, "serverSide":true, "order":[], "ajax":{ url:"", type:"POST" }, "columnDefs":[ { "targets":[0, 3, 4], "orderable":false, }, ], }); });