Web Development Using PHP with CodeIgniter 3 (CI3)
Introduction
Web development has seen a tremendous evolution over the years, with various frameworks emerging to streamline and expedite the process. Among them, CodeIgniter stands out as a lightweight yet powerful PHP framework. CodeIgniter 3 (CI3), although succeeded by CodeIgniter 4, remains widely used due to its simplicity, flexibility, and excellent documentation. This blog will guide you through web development using PHP with CI3, covering everything from installation to creating a simple appliampcation with code exles.
Why Choose CodeIgniter 3?
1. Lightweight Framework:
CI3 is designed to be lightweight. It doesn’t require a lot of configurations to start with, and it runs exceptionally fast compared to other PHP frameworks.
2. MVC Architecture:
CodeIgniter implements the Model-View-Controller (MVC) architecture, which promotes separation of concerns, making the codebase more maintainable and scalable.
3. Easy Learning Curve:
For developers familiar with PHP, CodeIgniter’s learning curve is relatively gentle. The framework’s excellent documentation makes it easier for beginners to start building web applications.
4. Flexibility:
CI3 is very flexible, allowing developers to use it as per their project’s requirements. It doesn’t enforce strict rules or structures, providing more control over the codebase.
Getting Started with CodeIgniter 3
Step 1: Installation
To start using CodeIgniter, you need to download the framework. Follow these steps:
- Download CodeIgniter:
- Visit the official CodeIgniter website and download the latest version of CodeIgniter 3.
bash Copy code wget https://github.com/bcit-ci/CodeIgniter/archive/3.1.11.zip unzip 3.1.11.zip
- Up the Environment:
- Move the extracted files to your web server’s root directory (e.g.,
htdocsfor XAMPP,wwwfor WAMP).
bash Copy code mv CodeIgniter-3.1.11 /var/www/html/my_ci_app
- Configuration:
- Open the
application/config/config.phpfile and configure the base URL.
php Copy code $config['base_url'] = 'http://localhost/my_ci_app/';
Step 2: Basic Structure of a CodeIgniter Application
CodeIgniter follows the MVC architecture. Let’s break down the structure:
- Models: Represent the data layer and contain the logic for interacting with the database.
- Views: Represent the presentation layer and are responsible for rendering the user interface.
- Controllers: Act as an intermediary between Models and Views, handling user input and sending it to the Model for processing.
Building a Simple Web Application
Let’s build a simple web application that allows users to create, read, update, and delete (CRUD) records of a “Books” table.
Step 1: Set Up the Database
- Create a Database:
- Create a new MySQL database for your application.
sql Copy code CREATE DATABASE ci_bookstore;
- Create a Table:
- Create a
bookstable with fields likeid,title,author, anddescription.
sql
Copy code
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
description TEXT NOT NULL
);
- Database Configuration:
- Configure the database settings in the
application/config/database.phpfile.
php
Copy code
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ci_bookstore',
'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
);
Step 2: Create a Model
Create a model that interacts with the books table. Models in CI3 are stored in the application/models/ directory.
File: application/models/Book_model.php
php
Copy code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Book_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function get_books($id = FALSE) {
if ($id === FALSE) {
$query = $this->db->get('books');
return $query->result_array();
}
$query = $this->db->get_where('books', array('id' => $id));
return $query->row_array();
}
public function add_book($data) {
return $this->db->insert('books', $data);
}
public function update_book($id, $data) {
$this->db->where('id', $id);
return $this->db->update('books', $data);
}
public function delete_book($id) {
$this->db->where('id', $id);
return $this->db->delete('books');
}
}
?>
Step 3: Create a Controller
Controllers in CI3 are stored in the application/controllers/ directory. Create a controller that handles the user’s requests.
File: application/controllers/Books.php
php
Copy code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Books extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Book_model');
$this->load->helper('url');
}
public function index() {
$data['books'] = $this->Book_model->get_books();
$this->load->view('books/index', $data);
}
public function view($id) {
$data['book'] = $this->Book_model->get_books($id);
if (empty($data['book'])) {
show_404();
}
$this->load->view('books/view', $data);
}
public function create() {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('books/create');
} else {
$this->Book_model->add_book($this->input->post());
redirect('books');
}
}
public function edit($id) {
$this->load->helper('form');
$this->load->library('form_validation');
$data['book'] = $this->Book_model->get_books($id);
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('books/edit', $data);
} else {
$this->Book_model->update_book($id, $this->input->post());
redirect('books');
}
}
public function delete($id) {
$this->Book_model->delete_book($id);
redirect('books');
}
}
?>
Step 4: Create Views
Views in CI3 are stored in the application/views/ directory. Create the following views:
- List of Books:
- File:
application/views/books/index.php
php
Copy code
<h2>Books List</h2>
<a href="<?php echo site_url('books/create'); ?>">Add New Book</a>
<ul>
<?php foreach ($books as $book): ?>
<li>
<a href="<?php echo site_url('books/view/'.$book['id']); ?>">
<?php echo $book['title']; ?>
</a>
- <a href="<?php echo site_url('books/edit/'.$book['id']); ?>">Edit</a>
- <a href="<?php echo site_url('books/delete/'.$book['id']); ?>">Delete</a>
</li>
<?php endforeach; ?>
</ul>
- View a Book:
- File:
application/views/books/view.php
php
Copy code
<h2><?php echo $book['title']; ?></h2>
<p>Author: <?php echo $book['author']; ?></p>
<p>Description: <?php echo $book['description']; ?></p>
<a href="<?php echo site_url('books'); ?>">Back to list</a>
- Create a Book:
- File:
application/views/books/create.php
php
Copy code
<h2>Add a New Book</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('books/create'); ?>
<label for="title">Title</label>
<input type="text" name="title" /><br />
<label for="author">Author</label>
<input type="text" name="author" /><br />
<label for="description">Description</label>
<textarea name="description"></textarea><br />
<input type="submit" name="submit" value="Add Book" />
</form>
- Edit a Book:
- File:
application/views/books/edit.php
php
Copy code
<h2>Edit Book: <?php echo $book['title']; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('books/edit/'.$book['id']); ?>
<label for="title">Title</label>
<input type="text" name="title" value="<?php echo $book['title']; ?>" /><br />
<label for="author">Author</label>
<input type="text" name="author" value="<?php echo $book['author']; ?>" /><br />
<label for="description">Description</label>
<textarea name="description"><?php echo $book['description']; ?></textarea><br />
<input type="submit" name="submit" value="Update Book" />
</form>
Step 5: Run the Application
You can now run the application by visiting http://localhost/my_ci_app/books in your browser. You’ll be able to perform CRUD operations on the books in your database.
Conclusion
CodeIgniter 3, while simple, provides robust tools for building dynamic web applications efficiently. By following this guide, you’ve created a basic CRUD application using CI3, which can serve as a foundation for more complex projects. The framework's lightweight nature, coupled with the MVC architecture, allows developers to maintain a clean codebase while delivering powerful web applications. Whether you’re a beginner or an experienced developer, CI3’s flexibility and ease of use make it a great choice for PHP development.
