Showing posts with label codeigniter. Show all posts
Showing posts with label codeigniter. Show all posts

Codeigniter Pagination Example (Query String )

Before Going through the complete article I assume that you have a basic idea of CodeIgniter,

Controller Code:

public function user_location($start_from = 0) {

        $offset = ($this->uri->segment(3) != '' ? $this->uri->segment(3) : 0);

        $config = array();
        $config["total_rows"] = $this->Reports_model->user_record_count();
        $config['per_page'] = 4;
        $config['full_tag_open'] = '
        $config['full_tag_close'] = '
';        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['uri_segment'] = 3;
        $config['use_page_numbers'] = TRUE;
        $config["base_url"] = base_url() . "reports/user_location";
        $config['suffix'] = '?' . http_build_query($_GET, '', "&");
        $config['first_url'] = base_url() . 'reports/user_location/?' . http_build_query($_GET, '', "&");

        $this->pagination->initialize($config);

        $data['links'] = $this->pagination->create_links();

        if (!empty($start_from)) {
            $start = $config['per_page'] * ($start_from - 1);
        } else {
            $start = 0;
        }

        $param = array();
        $param = $_GET;

        $data['results'] = $this->Reports_model->fetch_user($config["per_page"], $start, $param);


     
        $data['header'] = $this->load->view('main_header', '', true);
        $data['menu'] = $this->load->view('main_menu', '', true);
        $data['footer'] = $this->load->view('main_footer', '', true);

        $this->load->view('user_list', $data);
    }

Model Code :


public function fetch_user($limit, $start, $param) {
        $return_result = array();
        $this->db->select('user.mobile,user_type_master.name,user.city_name');
        $this->db->from('user');
        $this->db->join('user_type_master', 'user_type_master.id = user.user_type_id', 'LEFT');

        if (isset($param['user_type']) && !empty($param['user_type'])) {
            $this->db->where('user.user_type_id', $param['user_type']);
        }

        $this->db->limit($limit, $start);

        $result = $this->db->get();

        if ($result && $result->num_rows() > 0) {
            $return_result = $result->result_array();
            foreach ($return_result as $key => $value) {
                if (isset($value ['profile_image']) && !empty($value ['profile_image'])) {
                    $return_result [$key] ['profile_image'] = DESIGNS_MEDIA_URL . $value ['profile_image'];
                }
            }
        }

        return $return_result;

    }


View Code :

I don't think its required here.

Codeigniter Model ( Select, Insert , Update , Delete ) Snippets


class xyz_model extends CI_Model {

    const TABLE_NAME = 'xyz';

    public function __construct() {
        $this->load->database();
    }

    public function saveData($data) {
        $return_id = 0;
        if (!empty($data)) {
            $insert_status = $this->db->insert(self::TABLE_NAME, $data);
            if ($insert_status) {
                $return_id = $this->db->insert_id();
            }
        }
        return $return_id;
    }

    public function updateData($update_params, $condition_params) {
        $return_status = 0;
        if (!empty($update_params) && !empty($condition_params)) {
            $this->db->where($condition_params);
            $this->db->update(self::TABLE_NAME, $update_params);
            $return_status = $this->db->affected_rows();
        }
        return $return_status;
    }

    public function getData($id, $fields = '') {
        $return_result = array();
        if ($id > 0) {
            if (!empty($fields)) {
                $this->db->select($fields);
            }
            $result = $this->db->get_where(self::TABLE_NAME, array(
                'id' => $id
                    ), $limit = 1, $offset = 0);

            if ($result && $result->num_rows() > 0) {
                $return_result = $result->result_array();
            }
        }
        return $return_result;
    }

    public function delete($id) {
        return $this->db->delete(self::TABLE_NAME, array(
                    'id' => $id
        ));
    }

}

Save CI Session to DB Config

$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'cms_ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 7200;
$config['sess_expire_on_close'] = TRUE;

PHP Design Patterns

There are numerous ways to structure the code and project for your web application, and you can put as much or as little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make your code easier to manage and easier for others to understand.

Factory

One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the object you want to use. Consider the following example of the factory pattern:

class Automobile
{
    private $vehicleMake;
    private $vehicleModel;

    public function __construct($make, $model)
    {
        $this->vehicleMake = $make;
        $this->vehicleModel = $model;
    }

    public function getMakeAndModel()
    {
        return $this->vehicleMake . ' ' . $this->vehicleModel;
    }
}

class AutomobileFactory
{
    public static function create($make, $model)
    {
        return new Automobile($make, $model);
    }
}

// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');

print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way; the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead of repeating it every time you want to create a new instance.
Using the factory pattern isn’t always necessary (or wise). The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save yourself a lot of trouble down the road by using factories.

Singleton

When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only one instance of a particular class. The singleton pattern enables us to do this.

class Singleton
{
    /**
     * @var Singleton The reference to *Singleton* instance of this class
     */
    private static $instance;
    
    /**
     * Returns the *Singleton* instance of this class.
     *
     * @return Singleton The *Singleton* instance.
     */
    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        
        return static::$instance;
    }

    /**
     * Protected constructor to prevent creating a new instance of the
     * *Singleton* via the `new` operator from outside of this class.
     */
    protected function __construct()
    {
    }

    /**
     * Private clone method to prevent cloning of the instance of the
     * *Singleton* instance.
     *
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * Private unserialize method to prevent unserializing of the *Singleton*
     * instance.
     *
     * @return void
     */
    private function __wakeup()
    {
    }
}

class SingletonChild extends Singleton
{
}

$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());             // bool(true)

$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance());      // bool(false)

var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)
The code above implements the singleton pattern using a static variable and the static creation method getInstance(). Note the following:
  • The constructor __construct() is declared as protected to prevent creating a new instance outside of the class via the new operator.
  • The magic method __clone() is declared as private to prevent cloning of an instance of the class via the clone operator.
  • The magic method __wakeup() is declared as private to prevent unserializing of an instance of the class via the global function unserialize() .
  • A new instance is created via late static binding in the static creation methodgetInstance() with the keyword static. This allows the subclassing of the classSingleton in the example.
The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire request lifecycle in a web application. This typically occurs when we have global objects (such as a Configuration class) or a shared resource (such as an event queue).
You should be wary when using the singleton pattern, as by its very nature it introduces global state into your application, reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our application, as the object using the shared or global resource requires no knowledge of a concretely defined class.

Strategy

With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for instantiating a particular algorithm to have no knowledge of the actual implementation. There are several variations on the strategy pattern, the simplest of which is outlined below:
This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe just an array of data:


interface OutputInterface
{
    public function load();
}

class SerializedArrayOutput implements OutputInterface
{
    public function load()
    {
        return serialize($arrayOfData);
    }
}

class JsonStringOutput implements OutputInterface
{
    public function load()
    {
        return json_encode($arrayOfData);
    }
}

class ArrayOutput implements OutputInterface
{
    public function load()
    {
        return $arrayOfData;
    }
}
By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily add new output types without affecting the client code.
You will see how each concrete ‘output’ class implements an OutputInterface - this serves two purposes, primarily it provides a simple contract which must be obeyed by any new concrete implementations. Secondly by implementing a common interface you will see in the next section that you can now utilise Type Hinting to ensure that the client which is utilising these behaviours is of the correct type in this case ‘OutputInterface’.
The next snippet of code outlines how a calling client class might use one of these algorithms and even better set the behaviour required at runtime:

class SomeClient
{
    private $output;

    public function setOutput(OutputInterface $outputType)
    {
        $this->output = $outputType;
    }

    public function loadOutput()
    {
        return $this->output->load();
    }
}
The calling client class above has a private property which must be set at runtime and be of type ‘OutputInterface’ once this property is set a call to loadOutput() will call the load() method in the concrete class of the output type that has been set.

$client = new SomeClient();

// Want an array?
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput();

// Want some JSON?
$client->setOutput(new JsonStringOutput());
$data = $client->loadOutput();

Front Controller

The front controller pattern is where you have a single entrance point for your web application (e.g. index.php) that handles all of the requests. This code is responsible for loading all of the dependencies, processing the request and sending the response to the browser. The front controller pattern can be beneficial because it encourages modular code and gives you a central place to hook in code that should be run for every request (such as input sanitization).

Model-View-Controller

The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats usable throughout your application. Controllers handle the request, process the data returned from models and load views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the web browser.
MVC is the most common architectural pattern used in the popular PHP frameworks.
Learn more about MVC and its relatives:

Getting time difference between two times in PHP

$val1 '2014-03-18 10:34:09.939';$val2 '2014-03-18 10:34:09.940';
$datetime1 = new DateTime($val1);$datetime2 = new DateTime($val2);
echo 
"
"
;var_dump($datetime1->diff($datetime2));

if(
$datetime1 $datetime2)
  echo 
"1 is bigger";
else
  echo 
"2 is bigger";

?>

How to apply css styles to codeigniter dropdown?

form_dropdown('dropdown', $options, $selected, 'style="width: 240px; font-size: 13px"');
You could just as easily add a class to the  and then add the styles in your stylesheet:
form_dropdown('dropdown', $options, $selected, 'class="foo"');
In either case, if you don't have a value for $selected, set it to array()
form_dropdown('dropdown', $options, array(), 'style="width: 240px; font-size: 13px"');
Although you could get away setting it to null or '' for convenience.

SOAP-ERROR: Parsing WSDL: Couldn't load from

For some versions of php, the SoapClient does not send http user agent information. What php versions do you have on the server vs your local WAMP?
Try to set the user agent explicitly, using a context stream as follows:
try{

    $opts = array(
        'http'=>array(
            'user_agent' => 'PHPSoapClient'
            )
        );

    $context = stream_context_create($opts);
    $client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl',
                             array('stream_context' => $context,
                                   'cache_wsdl' => WSDL_CACHE_NONE));

    $result = $client->checkVat(array(
                                    'countryCode' => 'DK',
                                    'vatNumber' => '47458714'
                                    ));
    print_r($result);
}
catch(Exception $e){
    echo $e->getMessage();
}

if  still not work check below Conditions


The combination of HTTP over IPv6, and missing HTTP User Agent string, seems to give the web service problems.

To verify this, try the following on your linux host:
curl  -A ''  -6 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
this IPv6 request fails.
curl  -A 'cURL User Agent'  -6 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
this IPv6 request succeeds.
curl  -A ''  -4 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
curl  -A 'cURL User Agent'  -4 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
both these IPv4 request succeeds.
Interesting case :) I guess your linux host resolves ec.europa.eu to its IPv6 address, and that your version of SoapClient did not add a user agent string by default.

How to debug on production server

First of all its very bad practice to debug on the production server.

but sometime the situation arrives where we have to debug on the production server.


here is the few technique sharing to debug on production server.

1.  Debug Using Cookies.

Install Crome Extension cookies inspector .



Add Cookies Name : tester
Now Write A code to check is cookies is available or not

if(isset($_COOKIE['tester'])) {
    // Write your debug code here.
}



That all.

CodeIgniter Remove index.php By .htaccess

In this tutorial I am going to show how to remove index.php from URL using .htaccess file in CodeIgniter. htaccess is the shortened used for Hypertext Access, which is a powerful configuration file that controls the directory “.htaccess”. It is used by Apache based web servers to control various server features.
Now The Question Arises Why Exactly do we want to remove index.php..?? As CodeIgniter’s URLs are designed to be search engine friendly and to human too. And so to maintain the standards we need to remove the default index.php which appears in the url of codeigniter applications, so that the url becomes search engine friendly and looks clean.
The script contains the code with proper documentation to perform the following transformation.


Steps To Remove index.php using .htaccess:-

Step:-1  Open the file config.php located in application/config path.  Find and Replace the below code in config.php  file.
//  Find the below code

$config['index_page'] = "index.php"

//  Remove index.php

$config['index_page'] = ""
Step:-2  Go to your CodeIgniter folder and create .htaccess  file.

Path:
Your_website_folder/
application/
assets/
system/
user_guide/
.htaccess <--------- this file
index.php
license.txt
Step:-3  Write below code in .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Step:-4  In some cases the default setting for uri_protocol does not work properly. To solve this issue just open the file config.php located in application/configand then find and replace the code as:
//  Find the below code

$config['uri_protocol'] = "AUTO"

//  Replace it as

$config['uri_protocol'] = "REQUEST_URI" 

Conclusion:

Hope these steps helped you to remove index.php in CodeIgniter framework using .htaccess. Keep reading our blogs.