---
description: Data is the bloodline of most applications. The data needs to be stored in such a way that it can be further analyzed to provide insights and facilitate business decisions. The data is usually stored
title: "CodeIgniter Active Record: Insert, Update, Delete Query"
image: https://www.guru99.com/images/codeigniter-active-record-crud.png
---

[Skip to content](#main)

**⚡ Smart Summary**

CodeIgniter Active Record is a design pattern that lets a model read and write the database with simple, secure method chains. It supports insert, select, update, and delete across different database engines without rewriting code, and it parameterizes input to prevent SQL injection.

- 🔗 **Core Idea:** Active Record wraps SQL in method calls like insert, get, update, and delete.
- 🛡️ **Secure:** Values are passed as parameters, which protects against SQL injection.
- 🔄 **Portable:** The same code works across MySQL, SQL Server, and others through database drivers.
- ⚙️ **Setup:** Configure database.php and autoload the database library.
- ➕ **Insert:** $this->db->insert(‘table’, $data) builds and runs an INSERT.
- 🔍 **Select:** $this->db->get(‘table’) returns the rows to loop over.
- ✏️ **Update and Delete:** A where clause plus update or delete changes or removes rows.

Read More

![CodeIgniter Active Record CRUD](https://www.guru99.com/images/codeigniter-active-record-crud.png)

Data is the bloodline of most applications. It needs to be stored so that it can be analyzed to provide insights and facilitate business decisions. The data is usually stored in a database. Among the chief concerns when interacting with the database are security, ease of access, and database vendor-specific implementations of Structured Query Language (SQL).

Active Record is a design pattern that makes it easy to interact with the database in a secure and eloquent way. The Active Record has the following advantages:

- Insert, update, and delete records with simple method chains.
- Submits user input securely using parameters.
- Allows you to work with multiple database engines such as MySQL and SQL Server without rewriting the application code.
- CodeIgniter uses drivers specific to each database engine in the background.

## How to Use Active Record: Example

In this tutorial, we will use a sample database with two tables, one with orders and the other with details. This tutorial assumes you have a MySQL database installed and running. Run the following scripts to create the tutorial database:

```
CREATE SCHEMA ci_active_record;

USE ci_active_record;

CREATE TABLE `order_details` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) DEFAULT NULL,
`item` varchar(245) DEFAULT NULL,
`quantity` int(11) DEFAULT '0',
`price` decimal(10,2) DEFAULT '0.00',
`sub_total` decimal(10,2) DEFAULT '0.00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT = 1;

CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NULL DEFAULT NULL,
`customer_name` varchar(245) DEFAULT NULL,
`customer_address` varchar(245) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT = 1;
```

The code above creates a database named ci\_active\_record and two tables, orders and order\_details. The relationship between the two tables is defined by the column id in orders and order\_id in order\_details.

## CodeIgniter Database Configuration

We will now configure our application to communicate with this database. Open the database configuration file located in application/config/database.php and locate the following lines:

```
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
```

Update the code above to the following:

```
'hostname' => 'localhost',
'username' => 'root',
'password' => 'letmein',
'database' => 'ci_active_record',
```

**Note:** you will need to replace the username and password with the ones that match your [MySQL](https://www.guru99.com/mysql-tutorial.html) configuration.

In addition to the database configuration details, we also need to tell CodeIgniter to load the database library when it loads.

**Step 1)** Open the following file: application/config/autoload.php.

**Step 2)** Locate the $autoload array key libraries and load the database library as shown below:

```
$autoload['libraries'] = array('database');
```

**Here:**

- The code above loads the database library when the application starts.

## CodeIgniter Insert Active Record

For testing purposes, we will create a controller and define routes to interact with our application via Active Record. Create a new file application/controllers/ActiveRecordController.php and add the following code:

```
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class ActiveRecordController extends CI_Controller {
public function store_order(){
$data = [
'date' => '2018-12-19',
'customer_name' => 'Joe Thomas',
'customer_address' => 'US'
];

$this->db->insert('orders', $data);

echo 'order has successfully been created';
}
}
```

**Here:**

- $data = \[…] defines an array variable data that uses database table column names as array keys and assigns values to them.
- $this->db->insert(‘orders’, $data); calls the insert method of the database library, passing in the table name orders and the array variable $data. This line generates the SQL INSERT statement using the array keys as the field names and the array values as the values to be inserted.

Now that we have created the controller method, we need to create a route that we will call to execute it. Open application/config/routes.php and add the following line:

```
$route['ar/insert'] = 'activerecordcontroller/store_order';
```

**Here:**

- We define a route ar/insert that calls the store\_order method of the ActiveRecordController.

Let us now start the web server to test our method. Run the following command to start the built-in PHP server:

```
cd C:\Sites\ci-app
php -S localhost:3000
```

**Here:**

- The command above browses to the project directory and starts the built-in server at port 3000.

Load the following URL into your browser: `http://localhost:3000/ar/insert`. You will get the following result:

```
order has successfully been created
```

Open the MySQL tutorial database and check the orders table. You will see the newly created row, as shown in the image below:

[![New order row inserted via Active Record]()](https://www.guru99.com/images/1/011119_0545_Codeigniter1.png)

**Don't Miss:**

- [CodeIgniter Tutorial for Beginners](https://www.guru99.com/codeigniter-tutorial.html)
- [CodeIgniter Routes: URL Routing with Example](https://www.guru99.com/codeigniter-url-routing.html)
- [How to Upload Image & File in CodeIgniter (with Example)](https://www.guru99.com/codeigniter-file-upload.html)
- [How to Send Email using CodeIgniter](https://www.guru99.com/codeigniter-sending-email.html)

## CodeIgniter Select Active Record

In this section, we will see how to read the records in the database and display them in the web browser as an unordered list. Add the following method to the ActiveRecordController:

```
public function index() {
$query = $this->db->get('orders');

echo "<h3>Orders Listing</h3>";
echo "<ul>";

foreach ($query->result() as $row) {
echo "<li>$row->customer_name</li>";
}

echo "</ul>";
}
```

**Here:**

- $query = $this->db->get(‘orders’); runs the select query against the orders table, selecting all the fields.
- echo “\<h3>Orders Listing\</h3>”; displays an HTML heading.
- echo “\<ul>”; prints the opening tag for an unordered HTML list.
- foreach ($query->result() as $row) {…} loops through the results returned from the database, and echo “\<li>$row->customer\_name\</li>”; prints the customer\_name.

Before you load the URL, you can add a couple more records to the database. Let us now define a route for the SELECT query. Open application/config/routes.php and add the following route:

```
$route['ar'] = 'activerecordcontroller';
```

**Here:**

- The route ar points to the index method of the ActiveRecordController class. This is the default, which is why we did not specify the index method, as we did for the route that inserts records.

Assuming the web server is already running, load the following URL: `http://localhost:3000/ar`. You should see results similar to the following in your web browser:

[![Orders listing selected via Active Record]()](https://www.guru99.com/images/1/011119_0545_Codeigniter2.png)

## CodeIgniter Update Active Record

In this section, we will talk about how to use Active Record to update the database. Suppose we want to update the customer name Joe Thomas to Joe. Add the following method to the ActiveRecordController class:

```
public function update_order() {
$data = [
'customer_name' => 'Joe',
];
$this->db->where('id', 1);
$this->db->update('orders', $data);
echo 'order has successfully been updated';
}
```

**Here:**

- $data = \[…] defines the fields and values we wish to update in the database table.
- $this->db->where(‘id’, 1); sets the where clause of the update query.
- $this->db->update(‘orders’, $data); generates the SQL update query and executes it against our database.

The code above produces the following SQL statement:

```
UPDATE orders SET customer_name = 'Joe' WHERE id = 1;
```

Let us now update application/config/routes.php and add the following route:

```
$route['ar/update'] = 'activerecordcontroller/update_order';
```

Save the changes and load the following URL in the web browser:

[![Order successfully updated message]()](https://www.guru99.com/images/1/011119_0545_Codeigniter3.png)

Let us now display the database records and see if the change has taken effect.

[![Orders listing showing the updated name]()](https://www.guru99.com/images/1/011119_0545_Codeigniter4.png)

As you can see from the image above, the first record has been updated from Joe Thomas to Joe.

## CodeIgniter Delete Active Record

We will now delete a record from the database. We will delete the record with the id of 3. Add the following method to the ActiveRecordController:

```
public function delete_order() {
$this->db->where('id', 3);
$this->db->delete('orders');

echo 'order has successfully been deleted';
}
```

**Here:**

- $this->db->where(‘id’, 3); sets the where clause.
- $this->db->delete(‘orders’); deletes the database row in the orders table based on the criteria set using the where clause.

To execute the code above, load the following URL in your web browser: `http://localhost:3000/ar/delete`.

## FAQs

🛡️ How does Active Record protect against SQL injection?

Active Record binds values as parameters instead of concatenating them into the SQL string, so user input cannot alter the query structure. This escaping happens automatically for insert, update, and where.

🔄 Can the same Active Record code run on different databases?

Yes. Active Record generates SQL through a driver for each engine, so switching from MySQL to SQL Server usually means changing the config, not the model code, as long as you avoid vendor-specific SQL.

✏️ Why must I call where() before update() or delete()?

The where clause limits which rows the statement affects. Without it, an update or delete runs against every row in the table, which is a common and costly mistake.

🤖 Can AI convert raw SQL into Active Record calls?

Yes. AI can rewrite a SELECT, INSERT, UPDATE, or DELETE as the equivalent get, insert, update, or delete chain. Test the result, since complex joins may need the query builder rather than simple Active Record.

⚙️ Why autoload the database library?

Autoloading the database library makes $this->db available in every controller and model without loading it each time. It is convenient when most of the application talks to the database.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/codeigniter-active-record-crud.png","url":"https://www.guru99.com/images/codeigniter-active-record-crud.png","width":"700","height":"250","caption":"CodeIgniter Active Record (CRUD)","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/codeigniter-active-record.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/codeigniter","name":"CodeIgniter"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/codeigniter-active-record.html","name":"CodeIgniter Active Record: Insert, Update, Delete Query"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/codeigniter-active-record.html#webpage","url":"https://www.guru99.com/codeigniter-active-record.html","name":"CodeIgniter Active Record: Insert, Update, Delete Query","dateModified":"2026-07-22T17:21:12+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/codeigniter-active-record-crud.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/codeigniter-active-record.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/fiona","name":"Fiona Brown","description":"I'm Fiona brown, a Full Stack Developer with over a decade of experience, sharing practical guides on robust and scalable application development.","url":"https://www.guru99.com/author/fiona","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/fiona-brown-author.png","url":"https://www.guru99.com/images/fiona-brown-author.png","caption":"Fiona Brown","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"CodeIgniter","headline":"CodeIgniter Active Record: Insert, Update, Delete Query","description":"Data is the bloodline of most applications. The data needs to be stored in such a way that it can be further analyzed to provide insights and facilitate business decisions. The data is usually stored","keywords":"codeIgniter, php","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/fiona","name":"Fiona Brown"},"dateModified":"2026-07-22T17:21:12+05:30","image":{"@id":"https://www.guru99.com/images/codeigniter-active-record-crud.png"},"copyrightYear":"2026","name":"CodeIgniter Active Record: Insert, Update, Delete Query","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"How does Active Record protect against SQL injection?","acceptedAnswer":{"@type":"Answer","text":"Active Record binds values as parameters instead of concatenating them into the SQL string, so user input cannot alter the query structure. This escaping happens automatically for insert, update, and where."}},{"@type":"Question","name":"Can the same Active Record code run on different databases?","acceptedAnswer":{"@type":"Answer","text":"Yes. Active Record generates SQL through a driver for each engine, so switching from MySQL to SQL Server usually means changing the config, not the model code, as long as you avoid vendor-specific SQL."}},{"@type":"Question","name":"Why must I call where() before update() or delete()?","acceptedAnswer":{"@type":"Answer","text":"The where clause limits which rows the statement affects. Without it, an update or delete runs against every row in the table, which is a common and costly mistake."}},{"@type":"Question","name":"Can AI convert raw SQL into Active Record calls?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI can rewrite a SELECT, INSERT, UPDATE, or DELETE as the equivalent get, insert, update, or delete chain. Test the result, since complex joins may need the query builder rather than simple Active Record."}},{"@type":"Question","name":"Why autoload the database library?","acceptedAnswer":{"@type":"Answer","text":"Autoloading the database library makes the db object available in every controller and model without loading it each time. It is convenient when most of the application talks to the database."}}]}],"@id":"https://www.guru99.com/codeigniter-active-record.html#schema-1149089","isPartOf":{"@id":"https://www.guru99.com/codeigniter-active-record.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/codeigniter-active-record.html#webpage"}}]}
```
