Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, April 19, 2023

CodeIgniter Tutorial for Beginners

 

CodeIgniter is one of the most popular PHP framework based on MVC (Model–View–Controller) pattern. MVC is the most used pattern in web applications and most of PHP frameworks are based on this pattern. The MVC pattern divides an application into three parts: Model, View, Controller. The Model is responsible for handling data. The View is responsible for rendering the data provided by the model. The Controller is responsible to handle the Model and View to work together.

With CodeIgniter, you can easily develop small to large scale of applications based on MVC pattern. The CodeIgniter framework is very lightweight and easy to learn as it enables to develop projects much faster by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries.

So in this tutorial you will learn how to start with CodeIgniter to setup CodeIgniter framework to start with it quickly. We have also explain how to create CodeIgniter project to create live demo to display images list from MySQL database. 

 

Here we will cover this tutorial step by step to setup CodeIgniter and start developing project.


How to Setup CodeIgniter on Local Server

    • First download the latest version (currently CodeIgniter 3) of CodeIgniter from https://www.codeigniter.com/download
    • Extract the downloaded zip file and rename the folder according to your project. For example gallery/
    • Then keep your renamed CodeIgniter project folder codeigniter/ to your local server
    • Then try to open the project URL like http://localhost/gallery/, it ll see the following screen at the browser.


    • Then open the application/config/config.php file and set the $config[‘base_url’] variable value with your project base URL like http://localhost/gallery/
    • As you may also need to use database in your project, so open the application/config/database.php file and make following changes:
      • Change $db['default']['hostname'] value with your database hostname.
      • Change $db['default']['username'] value with your database username.
      • Change $db['default']['password'] value with your database password.
      • Change $db['default']['database'] value with your database name.
    • Then open the application/config/routes.php file and change $route['default_controller'] value from welcome to your project default controller that want to load by default. Here I have used gallery.
    • Then go to the application/controllers/ directory and create a PHP file called Gallery.php and open Gallery.php file and make following changes:
        • At the start of the file add the below codes for preventing the direct script access.
      <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
        • Then create a class named Gallery and extends this class from CI_Controller. The class name and file name must be same.
      class Gallery extends CI_Controller {
      }
    • Then go to the application/views/ directory and create a view file gallery_view.php for Gallery controller. Then open this gallery_view.php file and add some HTML code for testing purpose.
    • Then open the gallery_view controller application/controllers/gallery_view.php and add the following changes.
        • Create a index() function.
        • Load the view file into the index() function. The $this->load->view() statement is used for render the view.
      $this->load->view('gallery_view');
    • Now after above changes, reload the gallery URL http://localhost/gallery/, you’ll see the newly created Gallery controller view.


Work with Database using CodeIgniter

After CodeIgniter setup, now we will work with database with the CodeIgniter. Here we will create a demo gallery Codeigniter application in which we will access images from database and display using CodeIgniter. For this we have explained tutorial step by step.

Step 1. First we create a database and then create table gallery using below SQL statement.

CREATE TABLE IF NOT EXISTS `gallery` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Step 2. Then create a directory uploads/ in CodeIgniter root directory and insert few images into this directory. Then insert same images name into
gallery table in database.


Step 3. Now to connect with database to access, we have to define the database hostname, database username, database password and database name in the database.php file. So open the application/config/database.php file and change below values.

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'webdamn_demo';

Step 4. To use database with CodeIgniter, we need to load the CodeIgniter database library. We need to configure CodeIgniter to auto-load the database library. For this, open the file application/config/autoload.php and make the below changes.

    • Just find $autoload['libraries'] variable and set array(‘database’); value at this variable.
$autoload['libraries'] = array('database');

Step 5. Now we need to create a model into the models directory. Just follow the below steps:

    • Go to the application/models/ directory and create the file Gallery_model.php.
    • Then create a class and extend this class from CI_Model class. The class name should be the same of the file name, means the class name would be Gallery_model
    • Then create a function to get the records from the database. Here we have define get_images() function to fetch the images from the database.
    • Now the whole Gallery_model.php file code will be like below.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Gallery_model extends CI_Model {
    function get_images() {
        $query = $this->db->get('gallery');
        if($query->num_rows() > 0){
            $result = $query->result_array();
            return $result;
        }else{
            return false;
        }
    }
}

Step 6. Now Open the previously created application/controllers/Gallery.php file and below changes.

    • Load the model: $this->load->model('gallery_model')
    • Get images records from the model: $this->gallery_model->get_images()
    • Store the images data into an associative array: $data[‘gallery’] = $this->gallery_model->get_images();
    • Pass the images data to the view: $this->load->view('gallery_view', $data)
    • The full Gallery.php file code will be like below.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Gallery extends CI_Controller {	
	public function index()	{
		$this->load->model('gallery_model');
		$data['gallery'] = $this->gallery_model->get_images();
		$this->load->view('gallery_view', $data);		
	}
}

Step 7. Now open the previously created application/views/gallery_view.php file and add some code to display all images in gallery which are fetched from the controller. The complete code of gallery_view.php will be like below.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo: CodeIgniter Gallery application.</title>
</head>
<body>
<div id="container">
    <h1>CodeIgniter Gallery Application.</h1>
    <div id="body">
        <div class="gallery">
            <ul>
            <?php if(!empty($gallery)): foreach($gallery as $img): ?>
               <li><img src="uploads/<?php echo $img['image']; ?>" alt=""></li>
            <?php endforeach; endif; ?>
            </ul>
        </div>
    </div>
</div>
</body>
</html>

Step 8. After making all above changes, just reload page http://localhost/gallery/ to view your created images gallery.

No comments:

Post a Comment