Unit Testing Company India
Blazingcoders a testing firm in India provides excellent service in Unit testing, as it always important to find the bugs in the early stages of development, it is important to perform Unit testing. U
Read MoreSign Up Now and Get FREE CTO-level Consultation.
Building database-driven web applications becomes much easier when you understand the CRUD pattern. CRUD stands for Create, Read, Update, and Delete—the four basic operations used to manage records in a database.
In this tutorial, we will learn how to implement a basic CRUD operation in PHP CodeIgniter with a MySQL database. We will create a simple application for managing users, including adding, viewing, editing, and deleting user records.
This guide is designed for beginners who want a practical CodeIgniter CRUD example rather than just a theoretical explanation.
CRUD represents four fundamental database operations:
Create: Insert a new record into the database.
Read: Retrieve and display existing records.
Update: Modify an existing record.
Delete: Remove a record from the database.
CodeIgniter provides a lightweight MVC architecture and database tools that make these operations straightforward.
In a typical CodeIgniter application, the CRUD workflow looks like this:
User → View → Controller → Model → MySQL Database
For example, when a user submits a registration form, the request reaches the controller. The controller validates the request and calls the model. The model communicates with MySQL and inserts the record.
Before starting, make sure you have:
PHP installed on your development environment
CodeIgniter installed
MySQL or MariaDB
A local development server such as XAMPP, WAMP, or Laragon
Basic knowledge of PHP, HTML, and SQL
For new projects, use a currently supported CodeIgniter version and follow its official installation and configuration conventions.
First, create a database called crud_demo.
CREATE DATABASE crud_demo;
Select the database:
USE crud_demo;
Now create a users table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The table contains three important fields:
id uniquely identifies each user.
name stores the user's name.
email stores the user's email address.
The id field is automatically generated because it uses AUTO_INCREMENT.
The next step is to connect CodeIgniter to MySQL.
For a CodeIgniter 4 application, database configuration is commonly managed through the .env file.
Example:
database.default.hostname = localhost
database.default.database = crud_demo
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
database.default.port = 3306
Update the username, password, hostname, and database name according to your local environment.
Security tip: Do not publish production database credentials in source code or public repositories. Use environment-specific configuration and keep sensitive credentials private.
The model handles communication between the application and the database.
Create:
app/Models/UserModel.php
Example:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = [
'name',
'email'
];
}
The $table property tells CodeIgniter which database table the model uses.
The $allowedFields property is important because it controls which fields can be inserted or updated through the model. This is safer than blindly allowing every database column to be modified.
Now create a controller:
app/Controllers/UserController.php
A simple controller can look like this:
<?php
namespace App\Controllers;
use App\Models\UserModel;
class UserController extends BaseController
{
public function index()
{
$model = new UserModel();
$data['users'] = $model->findAll();
return view('users/index', $data);
}
public function create()
{
return view('users/create');
}
public function store()
{
$model = new UserModel();
$model->insert([
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email')
]);
return redirect()->to('/users');
}
public function edit($id)
{
$model = new UserModel();
$data['user'] = model->find(id);
return view('users/edit', $data);
}
public function update($id)
{
$model = new UserModel();
model->update(id, [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email')
]);
return redirect()->to('/users');
}
public function delete($id)
{
$model = new UserModel();
model->delete(id);
return redirect()->to('/users');
}
}
This controller demonstrates all four CRUD operations.
The store() method receives form data and inserts a new user.
The index() method uses findAll() to retrieve users and sends them to the view.
The update() method changes the selected record using its ID.
The delete() method removes the selected record.
Open:
app/Config/Routes.php
Add routes for the CRUD operations:
$routes->get('/users', 'UserController::index');
$routes->get('/users/create', 'UserController::create');
$routes->post('/users/store', 'UserController::store');
routes->get('/users/edit/(:num)','UserController::edit/1');
routes->post('/users/update/(:num)','UserController::update/1');
routes->get('/users/delete/(:num)','UserController::delete/1');
These routes connect browser requests to controller methods.
For production applications, use appropriate HTTP methods and CSRF protection rather than relying on a GET request for destructive actions.
Create:
app/Views/users/index.php
Example:
<h2>Users</h2>
<a href="/users/create">Add User</a>
<table border="1" cellpadding="10">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<?php foreach ($users as user):?><tr><td><?=esc(user['id']) ?></td>
<td><?= esc(user['name'])?></td><td><?=esc(user['email']) ?></td>
<td>
<a href="/users/edit/<?= $user['id'] ?>">Edit</a>
<a href="/users/delete/<?= $user['id'] ?>">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
Notice the use of esc() when displaying database values. Escaping output is an important security practice because it helps prevent malicious content from being interpreted as HTML.
Create:
app/Views/users/create.php
Example:
<h2>Add User</h2>
<form method="post" action="/users/store">
<label>Name</label>
<input type="text" name="name" required>
<br><br>
<label>Email</label>
<input type="email" name="email" required>
<br><br>
<button type="submit">Save</button>
</form>
When the form is submitted, the request is sent to the store() method.
For a production application, add server-side validation and CSRF protection rather than relying only on HTML's required attribute.
Create:
app/Views/users/edit.php
Example:
<h2>Edit User</h2>
<form method="post" action="/users/update/<?= user['id']?>"><label>Name</label><inputtype="text"name="name"value="<?=esc(user['name']) ?>"
required
>
<br><br>
<label>Email</label>
<input
type="email"
name="email"
value="<?= esc($user['email']) ?>"
required
>
<br><br>
<button type="submit">Update</button>
</form>
The existing user information is loaded from MySQL and displayed in the form. After submitting the form, the controller updates the corresponding record.
The application now follows a simple MVC structure:
app/
??? Controllers/
? ??? UserController.php
??? Models/
? ??? UserModel.php
??? Views/
? ??? users/
? ??? index.php
? ??? create.php
? ??? edit.php
??? Config/
??? Routes.php
The flow is:
Create: Form → Controller → Model → MySQL
Read: MySQL → Model → Controller → View
Update: Edit Form → Controller → Model → MySQL
Delete: Delete Request → Controller → Model → MySQL
Understanding this flow is more important than memorizing individual CodeIgniter functions because the same MVC pattern can be applied to products, orders, employees, categories, posts, and other database entities.
Check your database name, username, password, hostname, port, and database driver.
Make sure the field names in the HTML form match the names passed to the model and that the fields are included in $allowedFields.
Verify that the correct record ID is being passed to the update method and that the database record exists.
Check that the controller passes the expected data to the view and use esc() when displaying values.
Avoid implementing destructive operations through publicly accessible GET links in production. Prefer an appropriate request method, CSRF protection, authorization checks, and a confirmation step.
A basic CRUD example is useful for learning, but production applications need additional safeguards.
1. Validate user input
Validate required fields, email formats, string lengths, and other business rules on the server.
2. Use CSRF protection
Protect state-changing requests against cross-site request forgery.
3. Escape output
Use appropriate output escaping when displaying user-controlled or database content.
4. Implement authorization
Authentication alone is not enough. Confirm that the current user is authorized to edit or delete a particular record.
5. Avoid exposing database credentials
Keep production credentials outside publicly accessible source code.
6. Add pagination
If a table contains thousands of records, retrieving everything with findAll() may become inefficient. Use pagination for larger datasets.
7. Handle errors properly
Production applications should handle validation failures, database errors, missing records, and unauthorized requests gracefully.
Creating a basic CRUD application in PHP CodeIgniter with MySQL is an excellent way to understand MVC architecture and database-driven PHP development.
In this example, we created a MySQL users table, configured the database, built a UserModel, created a controller for CRUD operations, added routes, and created views for listing, adding, and editing users.
Once you understand this pattern, you can extend the same structure to build more advanced applications such as employee management systems, product catalogs, blog administration panels, customer management systems, and inventory applications.
The key takeaway is simple: the model manages data, the controller manages application logic, and the view presents the data to the user. Combining these components with CodeIgniter's database features gives you a clean foundation for building maintainable PHP applications.
CRUD stands for Create, Read, Update, and Delete. These operations allow a CodeIgniter application to insert, retrieve, modify, and remove records from a database.
Yes. CodeIgniter supports MySQL through its database layer. A CodeIgniter application can use models and database APIs to perform common database operations.
A typical CodeIgniter CRUD application includes a model, controller, views, routes, and database configuration.
Yes. CodeIgniter's relatively lightweight architecture makes it a practical framework for learning PHP MVC concepts and building database-driven applications.
Use server-side validation, CSRF protection, output escaping, authorization checks, secure database credentials, and appropriate HTTP methods for state-changing operations.
Request a FREE Business Plan.
+91 ▼ Blazingcoders a testing firm in India provides excellent service in Unit testing, as it always important to find the bugs in the early stages of development, it is important to perform Unit testing. U
Read More
With so many economical, accessible and customizable platforms, it’s never been easier to create an online store or even sell through established marketplaces like eBay and Amazon that provide t
Read More
Planning an event today is no longer just about booking a venue and sending invitations. From registrations and marketing to live check-ins and post-event analytics, modern events demand speed, accura
Read More