CodeIgniter Code Snippets

CodeIgniter is a powerful open-source PHP framework used for rapid web development. It is known for its simple and elegant syntax, as well as its flexibility and ability to scale. CodeIgniter has a wide range of built-in libraries and helpers that make common tasks easier, and its documentation is excellent.

However, because of its minority, finding quality CodeIgniter code snippets can be a challenge. To help make your life easier, we have curated a list of the best CodeIgniter code snippets. These snippets are hand-picked and organized by category, so you can easily find what you need.

Database

Connect to Multiple Databases —
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => '192.168.1.3',
	'username' => 'user2',
	'password' => 'passpass',
	'database' => 'database2',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);
//query
$db = $this->load->database('seconddatabase', TRUE);
$query = $db->select('*')->from('article')->where($conditions)->order_by('id', 'DESC')->get();
$result = $query->result();
Count Query Results —
//num_rows()
$this->db->select('count(*)');
$this->db->from('students');
$this->db->where('class_id', '7');
$query = $this->db->get();
echo $query->num_rows();
//use count_all_results()
$this->db->select('*');
$this->db->from('comments');
$this->db->where('comment LIKE', '%developers%');
$counter = $this->db->count_all_results();
Duplicate a Record Based on Id —
function duplicate($id, $count) {
    $this->db->where('id', $id);
    $query = $this->db->get($table);
    foreach ($query->result() as $row){
        foreach($row as $key => $val){
            if($key != 'id'){                
                $this->db->set($key, $val);
            }
        }
    }        
    $result = array();
    for ($i=0; $i < $count; $i++) { 
        $result[] = $this->db->insert($table);
    }

    return $result;
}
Get the Last Inserted ID —
$this->db->set('website', 'tleapps.com');
$this->db->set('type', 'blog');
$inserted = $this->db->insert("table_website");
if($inserted){
    $last_id = $this->db->insert_id();
}

Debug & Profiling

Generate Dummy Data —
$faker = Faker\Factory::create();

echo $faker->numberBetween(10, 1000);
echo $faker->email;
echo $faker->username;
echo $faker->hexcolor();
echo $faker->phoneNumber;
echo $faker->unixTime();

Form

Upload Multiple Files —
class FileManager extends MY_Controller {

	public function __construct()
	{
		parent::__construct();
	}

	/*
	** Upload images
	*/
	public function upload(){

		/* Form Helpers */
		$this->load->helper('form');
		$this->load->library('form_validation');

		if ($this->form_validation->run() == TRUE){

			$description = $this->input->post('description');

			//Upload images
			$upload_folder = date('Ym');
			$config['upload_path'] = './uploads/'.$upload_folder;
			$config['allowed_types'] = 'gif|jpg|jpeg|png';
			$config['max_size'] = 20480;
			$config['max_width'] = 10240;
			$config['max_height'] = 10240;
			$config['file_ext_tolower'] = TRUE;

			$this->load->library('upload', $config);

			if (!is_dir('./uploads/' . $upload_folder)) {
				mkdir('./uploads/' . $upload_folder, 0777, true);
			}

			if(isset($_FILES['images']) && $_FILES['images']['name'][0] != ""){
				$files_count = count($_FILES['images']['name']);
				for($i = 0; $i < $files_count; $i++){
				$_FILES['image']['name'] = $_FILES['images']['name'][$i];
				$_FILES['image']['type'] = $_FILES['images']['type'][$i];
				$_FILES['image']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
				$_FILES['image']['error'] = $_FILES['images']['error'][$i];
				$_FILES['image']['size'] = $_FILES['images']['size'][$i];

				if($this->upload->do_upload('image')){
					$image = $this->upload->data();
					//insert database or other task goes here
				} else {
					echo $this->upload->display_errors();
					die;
				}			

			}

		} else {

			$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
			$this->data['message_type'] = 'warning';

			$this->data['description'] = array(
			'name' => 'description',
			'id' => 'description',
			'rows' => 5,
			'cols' => 60,
			'value' => $this->form_validation->set_value('description'),
			'class' => 'form-control',
			);

			/* Load Template */
			$this->load->view('file/upload', $this->data);
		}
	}	

}
Get a Form's GET and POST Data —
//get
$name= $this->input->get('name');
$description = $this->input->get('description');
$password = $_GET['password'];
$country = $_GET['country'];

//post
$id = $this->input->post('id');
$validationCode = $this->input->post('validationCode');
$token = $_POST['token'];
$hash = $_POST['hash'];
Use is_unique in Form Update Validation —
if(trim($user->zipcode) != trim($this->input->post('zipcode'))){
    $this->form_validation->set_rules('zipcode', 'Zip', 'required|is_unique[user.zipcode]');
} else {
    $this->form_validation->set_rules('zipcode', 'Zip', 'required');
}

Menu & Navigation

Generate Dynamic Sitemap —
//controller
class Sitemap extends CI_Controller {    
    public function index()
    {
        $this->load->database();
        $query = $this->db->get("articles");
        $data['articles'] = $query->result();

        $this->load->view('sitemap', $data);
    }
}
//view
<?xml version="1.0" encoding="UTF-8">
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?php echo base_url();?></loc>
        <priority>1.0</priority>
        <changefreq>daily</changefreq>
    </url>
    
    <?php foreach($articles as $article) { ?>
    <url>
        <loc><?php echo base_url()."article/".$article->id ?></loc>
        <lastmod><?php echo date('c', $article->date); ?></lastmod>     
        <changefreq>daily</changefreq>
        <priority>1</priority>
    </url>
    <?php } ?>
</urlset>
Convert Title to URL Slug —
$title = "CodeIgniter Can Be Used to Make a Blog Platform";
$url_title = url_title($title, '-', true);
//output: codeigniter-can-be-used-to-make-a-blog-platform

Troubleshoot

CodeIgniter 3 HMVC error running on PHP 7 —
public function set_class($class)
    {
        $suffix = (string) $this->config->item('controller_suffix');
        if ($suffix && strpos($class, $suffix) === FALSE) {
            $class .= $suffix;
        }

        parent::set_class($class);
    }

Variable

Where to Declare Global Variables —
$GLOBALS['primaryColor'] = '#FF00F0';

global $appName;
$appName= 'Color Picker';

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close