PHPackages                             faqzul/codeigniter-crud-model - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Admin Panels](/categories/admin)
4. /
5. faqzul/codeigniter-crud-model

ActiveLibrary[Admin Panels](/categories/admin)

faqzul/codeigniter-crud-model
=============================

Create one model for all CodeIgniter controllers.

3.2.2(3y ago)962711[1 PRs](https://github.com/FaqZul/CodeIgniter-CRUD-Model/pulls)1MITPHPPHP &gt;=5.4.8

Since Oct 19Pushed 3y agoCompare

[ Source](https://github.com/FaqZul/CodeIgniter-CRUD-Model)[ Packagist](https://packagist.org/packages/faqzul/codeigniter-crud-model)[ Docs](https://github.com/FaqZul)[ RSS](/packages/faqzul-codeigniter-crud-model/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (7)DependenciesVersions (9)Used By (1)

CodeIgniter-CRUD-Model
======================

[](#codeigniter-crud-model)

Create one model for all CodeIgniter controllers, or You can extends this class in Your model class.

Getting Started
---------------

[](#getting-started)

### Composer

[](#composer)

```
git@FaqZul:/var/www/CodeIgniter$ composer require faqzul/codeigniter-crud-model
```

Prerequisites
-------------

[](#prerequisites)

- PHP version 5.6 or newer is recommended.
    It should work on 5.4.8 as well, but we strongly advise you NOT to run such old versions of PHP, because of potential security and performance issues, as well as missing features.
- [CodeIgniter 3.x](https://www.codeigniter.com/download)

Configuration
-------------

[](#configuration)

- Change the following line in the `application/config/autoload.php` file for use in Your controller class.

```
$autoload['packages'] = array();
↓
$autoload['packages'] = array(FCPATH . 'vendor/faqzul/codeigniter-crud-model');
```

- Change the following line in the `application/config/config.php` file for extends in Your model class.

```
$config['composer_autoload'] = FALSE;
↓
$config['composer_autoload'] = FCPATH . 'vendor/autoload.php';
```

### Setting CRUD Preferences

[](#setting-crud-preferences)

There are 4 different preferences available to suit Your needs. You can set it up manually as described here, or automatically via the preferences stored in Your configuration file, described below:

Preferences are set by passing an array of preference values to the crud initialize method. Here is an example of how You might set some preferences:

```
$this->load->model('crud');

$config['delete_record'] = TRUE;
$config['log_query'] = FALSE;
$config['track_trans'] = FALSE;

$this->crud->initialize($config);
```

> **ℹ️ Note**
> Most of the preferences have default values that will be used if You do not set them.

### Setting CRUD Preferences in a Config File

[](#setting-crud-preferences-in-a-config-file)

If You prefer not to set preferences using the above method, You can instead put them into a [config file](https://github.com/FaqZul/CodeIgniter-CRUD-Model/tree/3.2.2/config). Simply create a new file called the [crud.php](https://github.com/FaqZul/CodeIgniter-CRUD-Model/blob/3.2.2/config/crud.php), add the $config array in that file. Then save the file at [config/crud.php](https://github.com/FaqZul/CodeIgniter-CRUD-Model/blob/3.2.2/config/crud.php) and it will be used automatically. You will NOT need to use the `$this->crud->initialize()` method if You save Your preferences in a config file.

### CRUD Preferences

[](#crud-preferences)

Here is a list of all the options that can be set when using the crud class.

PreferencesDefault ValueOptionsDescriptiondbgroupdefaultNoneLets You choose which connection group to make activedelete\_recordTRUETRUE or FALSE
(boolean).TRUE: Your data will be deleted permanently.
FALSE: Your data able to be recovered (un-deleted).insert\_id\_keyNULLNoneIf using the PDO driver with PostgreSQL, or using the Interbase driver, this preference which specifies the appropriate sequence to check for the insert id.log\_queryFALSETRUE or FALSE
(boolean).Save the last query that was run.track\_transFALSETRUE or FALSE
(boolean).To know the data (when and who) created or updated.Usage
-----

[](#usage)

### createData

[](#createdata)

```
class Welcome extends CI_Controller {

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

	public function add() {
		$data = array(
			'user_email' => 'faqzul@gmail.com',
			'user_name' => 'FaqZul'
		);
		$a = $this->crud->createData('users', $data, TRUE);
		if ($a['message'] === '') {
			// Success inserting data.
			$profile = array(
				'user_id' => $a['insert_id'],			// it's the same $this->crud->insert_id().
				'link' => 'https://github.com/FaqZul'
			);
			$this->crud->createData('user_profiles', $profile);	// Without callback.
			$id = $this->crud->insert_id();				// Without callback, You can also get insert_id as well.
			redirect("profile?id=$id");
		}
		else {
			// Fail inserting data.
			echo var_dump($a);
		}
	}

	/* Example for insert batch */
	public function insert_batch() {
		$datas = array();
		for ($i = 0; $i < 100; $i++) {
			$data["user_email"] = "faqzul$i@gmail.com";
			$data["user_name"] = "FaqZul$i";
			array_push($datas, $data);
		}
		$a = $this->crud->createData('users', $datas);
		/* For get insert_id in every data, please use method insert_ids() */
		echo var_dump($this->crud->insert_ids());
	}

}
```

> **ℹ️ Note**
> To use $this-&gt;crud-&gt;insert\_id() or $this-&gt;crud-&gt;insert\_ids() if using the PDO driver with PostgreSQL, or using the Interbase driver, requires preference `insert_id_key` which specifies the appropriate sequence to check for the insert id.

```
$config['insert_id_key'] = 'SequenceName';
$this->crud->initialize($config);
```

### readData

[](#readdata)

```
class Welcome extends CI_Controller {

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

	public function list($page = 0) {
		$a = $this->crud->readData('*', 'users')->result();
		// This method returns the query result as an array of objects, or an empty array on failure. Typically you’ll use this in a foreach loop.
		// Executes: SELECT * FROM users

		$where = array('username' => 'FaqZul');
		$b = $this->crud->readData('*', 'users', $where)->row();
		// This method returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object.
		// Executes: SELECT * FROM users WHERE username = 'FaqZul'

		$join = array('user_profiles' => 'users.id = user_profiles.user_id');
		$where = array('username !=' => 'FaqZul');
		$c = $this->crud->readData('*', 'users', $where, $join, '', 'users.id DESC', array(10, $page * 10))->result_array();
		// This method returns the query result as a pure array, or an empty array when no result is produced. Typically you’ll use this in a foreach loop.
		// Executes: SELECT * FROM users JOIN user_profiles ON users.id = user_profiles.user_id WHERE username != 'FaqZul' ORDER BY users.id DESC LIMIT 10
	}

	public function search($q = '') {
		/* You can use more specific LIKE queries. */
		$like = array(array('like' => array('user_name' => $q)), 'or_like' => array('user_email' => $q));
		/* Or You can use it. */
		$like = array('or_like' => array('user_name' => $q, 'user_email' => $q));
		// Executes: WHERE user_name LIKE '%$q%' OR user_email LIKE '%$q%'
		$a = $this->crud->readData('*', 'users', $like)->result_array();
		echo json_encode($a);
	}

	public function user() {
		/* Only show users who are guests or owners. */
		$where = ['or_where' => [['role' => 'guest'], ['role' => 'owner']]];
		$a = $this->crud->readData('*', 'users', $where)->result_array();
		echo json_encode($a);
	}

	// See: https://codeigniter.com/user_guide/database/query_builder.html#query-grouping
	public function search_group() {
		$where = ['a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd'];
		$this->crud->group_set([0 => 'group_start', 1 => 'or_group_start']);
		$this->crud->group_end([2 => 2]);
		echo $this->crud->readDataQuery('*', 'mytable', $where);
		// Print: SELECT * FROM "mytable" WHERE ( "a" = 'a' OR ( "b" = 'b' AND "c" = 'c' ) ) AND "d" = 'd'

		// Search username administrator or superadmin in role admin
		$where = ['role' => 'admin', 'or_where' => [['username' => 'administrator'], ['username' => 'superadmin']]];
		echo $this->crud->group_set([1 => 'group_start'])->group_end([1 => 1])->readDataQuery('*', 'user', $where);
		// Print: SELECT * FROM "user" WHERE "role" = 'admin' AND ( "username" = 'administrator' OR "username" = 'superadmin' )
	}

}
```

> **ℹ️ Note**
> Now, you can use queries JOIN, LIKE, WHERE more specific. [See ChangeLog](https://github.com/FaqZul/CodeIgniter-CRUD-Model/blob/3.2.2/CHANGELOG.md)
> If preference `delete_record` FALSE, automatically add `WHERE TABLENAME_delete_date IS NULL` in Your query.

### updateData

[](#updatedata)

```
class Welcome extends CI_Controller {

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

	public function edit($id = 0) {
		$data = array('link' => 'https://github.com/FaqZul/CodeIgniter-CRUD-Model');
		echo ($this->crud->updateData('user_profiles', $data, array('user_id' => $id))) ? 'Success updating data.': $this->crud->error_message();
	}

}
```

### deleteData

[](#deletedata)

```
class Welcome extends CI_Controller {

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

	public function delete($id = 0) {
		if ($this->crud->deleteData('users', array('id' => $id))) {
			// Success deleting data.
			$this->crud->deleteData('user_profiles', array('user_id' => $id));
		}
		else {
			// Fail deleting data.
			echo var_dump($this->crud->error());
		}
	}

}
```

### extends

[](#extends)

```
class Blog_model extends Crud {

	public function __construct() {
		parent::__construct();
		// You can initialize crud in here.
		// $this->initialize($config);
	}

	public function get_entries() {
		$query = $this->readData('*', 'entries');
		return $query->result_array();
	}

	public function insert_entry() {
		$insert = array(
			'title' => $_POST['title'], // please read the below note.
			'content' => $_POST['content'],
			'date' => time()
		);
		$this->createData('entries', $insert);
	}

	public function update_entry() {
		$update = array(
			'title' => $_POST['title'], // please read the below note.
			'content' => $_POST['content'],
			'date' => time()
		);
		$this->updateData('entries', $update, array('id' => $_POST['id']));
	}

}
```

> **ℹ️ Note**
> For the sake of simplicity in this example we’re using `$_POST` directly. This is generally bad practice, and a more common approach would be to use the [Input Library](https://www.codeigniter.com/userguide3/libraries/input.html) `$this->input->post('title')`.

Class Reference
---------------

[](#class-reference)

> createData($table, $data \[, $callback = FALSE \])

- Parameters:
    - $table (string) - Table name.
    - $data (array) - An associative array of field/value pairs.
- Returns:
    - `$callback = FALSE` TRUE on success, FALSE on failure.
    - `$callback = TRUE`
        - code (int) - SQL error code.
        - insert\_id (int) - [The insert ID number when performing database inserts](https://www.codeigniter.com/user_guide/database/helpers.html?highlight=insert_id).
        - insert\_ids (array) - Insert ID from insert\_batch.
        - message (string) - SQL error message.
- Return Type: mixed.

> createDataQuery($table, $data)

- Parameters:
    - $table (string) - Table name.
    - $data (array) - An associative array of field/value pairs.
- Returns: Compiles an INSERT statement and returns it as a string.
- Return Type: string.

> readData($select, $from \[, $where = NULL \[, $joinTable = NULL \[, $groupBy = NULL \[, $orderBy = NULL \[, $limit = NULL \] \] \] \] \])

- Parameters:
    - $select (string) - The SELECT portion of a query.
    - $from (mixed) - Table name(s); array or string.
    - $where (mixed) - The WHERE clause; array or string.
    - $joinTable (array) - An associative array of table/condition pairs.
    - $groupBy (mixed) - Field(s) to group by; array or string.
    - $orderBy (string) - Field to order by. The order requested - ASC, DESC or random.
    - $limit (array) - Adds LIMIT and OFFSET clauses to a query. `array(10, 20)`.
        1. Key `0` (int) - Number of rows to limit the result to.
        2. Key `1` (int) - Number of rows to skip.
- Returns: There are several ways to generate query results:
    - [Result Arrays](https://www.codeigniter.com/userguide3/database/results.html#result-arrays).
    - [Result Rows](https://www.codeigniter.com/userguide3/database/results.html#result-rows).
    - [Custom Result Objects](https://www.codeigniter.com/userguide3/database/results.html#custom-result-objects).
    - [Result Helper Methods](https://www.codeigniter.com/userguide3/database/results.html#result-helper-methods).
- Return Type: [CI\_DB\_result](https://www.codeigniter.com/user_guide/database/results.html).

> readDataQuery($select, $from \[, $where = NULL \[, $joinTable = NULL \[, $groupBy = NULL \[, $orderBy = NULL \[, $limit = NULL \] \] \] \] \])

- Parameters:
    - $select (string) - The SELECT portion of a query.
    - $from (mixed) - Table name(s); array or string.
    - $where (mixed) - The WHERE clause; array or string.
    - $joinTable (array) - An associative array of table/condition pairs.
    - $groupBy (mixed) - Field(s) to group by; array or string.
    - $orderBy (string) - Field to order by. The order requested - ASC, DESC or random.
    - $limit (array) - Adds LIMIT and OFFSET clauses to a query. `array(10, 20)`.
        1. Key `0` (int) - Number of rows to limit the result to.
        2. Key `1` (int) - Number of rows to skip.
- Returns: Compiles a SELECT statement and returns it as a string.
- Return Type: string.

> updateData($table, $data, $where \[, $callback = FALSE \])

- Parameters:
    - $table (string) - Table name.
    - $data (array) - An associative array of field/value pairs.
    - $where (mixed) - The WHERE clause; array or string.
- Returns:
    - `$callback = FALSE` TRUE on success, FALSE on failure.
    - `$callback = TRUE` error() method.
- Return Type: mixed.

> updateDataQuery($table, $data, $where)

- Parameters:
    - $table (string) - Table name.
    - $data (array) - An associative array of field/value pairs.
    - $where (mixed) - The WHERE clause; array or string.
- Returns: Compiles an UPDATE statement and returns it as a string.
- Return Type: string.

> deleteData($table, $where \[, $callback = FALSE \])

- Parameters:
    - $table (string) - Table name.
    - $where (mixed) - The WHERE clause; array or string.
- Returns:
    - `$callback = FALSE` TRUE on success, FALSE on failure.
    - `$callback = TRUE` error() method.
- Return Type: mixed.

> deleteDataQuery($table, $where)

- Parameters:
    - $table (string) - Table name.
    - $where (mixed) - The WHERE clause; array or string.
- Returns: Compiles a DELETE statement and returns it as a string.
- Return Type: string.

> error()

- Returns:
    - code (int) - SQL error code.
    - message (string) - SQL error message.
- Return Type: array.

> error\_code()

- Returns: SQL error code.
- Return Type: int.

> error\_message()

- Returns: SQL error message.
- Return Type: string.

> insert\_id()

- Returns: [The insert ID number when performing database inserts](https://www.codeigniter.com/user_guide/database/helpers.html?highlight=insert_id).
- Return Type: int.

> insert\_ids()

- Returns: [The insert ID number when performing database inserts](https://www.codeigniter.com/user_guide/database/helpers.html?highlight=insert_id).
- Return Type: array.

Contributing
------------

[](#contributing)

Please read [CONTRIBUTING.md](https://github.com/FaqZul/CodeIgniter-CRUD-Model/blob/3.2.2/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

Versioning
----------

[](#versioning)

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/FaqZul/CodeIgniter-CRUD-Model/tags).

Authors
-------

[](#authors)

- **Muhammad Faqih Zulfikar** - *Developer*
    See also the list of [contributors](https://github.com/FaqZul/CodeIgniter-CRUD-Model/contributors) who participated in this project.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](https://github.com/FaqZul/CodeIgniter-CRUD-Model/blob/3.2.2/LICENSE) file for details.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~316 days

Recently: every ~470 days

Total

7

Last Release

1225d ago

Major Versions

1.0.0 → 2.0.02017-10-25

2.0.0 → 3.0.02017-11-08

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/32939170?v=4)[FaqZul](/maintainers/FaqZul)[@FaqZul](https://github.com/FaqZul)

---

Top Contributors

[![FaqZul](https://avatars.githubusercontent.com/u/32939170?v=4)](https://github.com/FaqZul "FaqZul (12 commits)")

---

Tags

codeignitermodelcrudfaqzul

### Embed Badge

![Health badge](/badges/faqzul-codeigniter-crud-model/health.svg)

```
[![Health](https://phpackages.com/badges/faqzul-codeigniter-crud-model/health.svg)](https://phpackages.com/packages/faqzul-codeigniter-crud-model)
```

###  Alternatives

[backpack/crud

Quickly build admin interfaces using Laravel, Bootstrap and JavaScript.

3.4k3.4M207](/packages/backpack-crud)[jamierumbelow/codeigniter-base-model

CodeIgniter base CRUD model to remove repetition and increase productivity

1.0k2.6k](/packages/jamierumbelow-codeigniter-base-model)[appzcoder/crud-generator

Laravel CRUD Generator

1.4k581.4k7](/packages/appzcoder-crud-generator)[friendsofcake/crud

CakePHP Application development on steroids - rapid prototyping / scaffolding &amp; production ready code - XML / JSON APIs and more

3751.4M25](/packages/friendsofcake-crud)[ibex/crud-generator

Laravel CRUD Generator

706235.0k](/packages/ibex-crud-generator)[backpack/pagemanager

Create admin panels for presentation websites on Laravel, using page templates and Backpack\\CRUD.

371522.6k6](/packages/backpack-pagemanager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
