Delete sql in codeigniter not in top 100 năm 2024

The CodeIgniter’s Model provides convenience features and additional functionality that people commonly use to make working with a single table in your database more convenient.

It comes out of the box with helper methods for much of the standard ways you would need to interact with a database table, including finding records, updating records, deleting records, and more.

Models are typically stored in the app/Models directory. They should have a namespace that matches their location within the directory, like

<?php $user = $userModel->find($user_id);

6.

You can access models within your classes by creating a new instance or using the helper function.

<?php // Create a new class manually. $userModel = new \App\Models\UserModel(); // Create a shared instance of the model. $userModel = model('UserModel'); // or $userModel = model('App\Models\UserModel'); // or $userModel = model(\App\Models\UserModel::class); // Create a new class with the model() function. $userModel = model('UserModel', false); // Create shared instance with a supplied database connection. $db = db_connect('custom'); $userModel = model('UserModel', true, $db);

The

<?php $user = $userModel->find($user_id);

7 uses

<?php $user = $userModel->find($user_id);

9 internally. See for details on the first parameter.

CodeIgniter does provide a model class that provides a few nice features, including:

  • automatic database connection
  • basic CRUD methods
  • in-model validation
  • and more

This class provides a solid base from which to build your own models, allowing you to rapidly build out your application’s model layer.

To take advantage of CodeIgniter’s model, you would simply create a new model class that extends

<?php $users = $userModel->find([1, 2, 3]);

0:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

This empty class provides convenient access to the database connection, the Query Builder, and a number of additional convenience methods.

Should you need additional setup in your model you may extend the

<?php $users = $userModel->find([1, 2, 3]);

1 method which will be run immediately after the Model’s constructor. This allows you to perform extra steps without repeating the constructor parameters, for example extending other models:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

When the class is first instantiated, if no database connection instance is passed to the constructor, and if you don’t set the

<?php $users = $userModel->find([1, 2, 3]);

2 property on your model class, it will automatically connect to the default database group, as set in the database configuration.

You can modify which group is used on a per-model basis by adding the

<?php $users = $userModel->find([1, 2, 3]);

2 property to your class. This ensures that within the model any references to

<?php $users = $userModel->find([1, 2, 3]);

4 are made through the appropriate connection.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

You would replace “group_name” with the name of a defined database group from the database configuration file.

The model class has some configuration options that can be set to allow the class’ methods to work seamlessly for you. The first two are used by all of the CRUD methods to determine what table to use and how we can find the required records:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

Specifies the database table that this model primarily works with. This only applies to the built-in CRUD methods. You are not restricted to using only this table in your own queries.

This is the name of the column that uniquely identifies the records in this table. This does not necessarily have to match the primary key that is specified in the database, but is used with methods like

<?php $users = $userModel->find([1, 2, 3]);

5 to know what column to match the specified value to.

Note

All Models must have a primaryKey specified to allow all of the features to work as expected.

Specifies if the table uses an auto-increment feature for . If set to

<?php $users = $userModel->find([1, 2, 3]);

6 then you are responsible for providing primary key value for every record in the table. This feature may be handy when we want to implement 1:1 relation or use UUIDs for our model. The default value is

<?php $users = $userModel->find([1, 2, 3]);

7.

Note

If you set to

<?php $users = $userModel->find([1, 2, 3]);

6, then make sure to set your primary key in the database to

<?php $users = $userModel->find([1, 2, 3]);

9. This way you will make sure that all of Model’s features will still work the same as before.

The Model’s CRUD methods will take a step of work away from you and automatically return the resulting data, instead of the Result object. This setting allows you to define the type of data that is returned. Valid values are ‘array’ (the default), ‘object’, or the fully qualified name of a class that can be used with the Result object’s

<?php $user = $userModel->findColumn($column_name);

0 method. Using the special

<?php $user = $userModel->findColumn($column_name);

1 constant of the class will allow most IDEs to auto-complete the name and allow functions like refactoring to better understand your code.

If true, then any

<?php $user = $userModel->findColumn($column_name);

2 method calls will set

<?php $user = $userModel->findColumn($column_name);

3 in the database, instead of actually deleting the row. This can preserve data when it might be referenced elsewhere, or can maintain a “recycle bin” of objects that can be restored, or even simply preserve it as part of a security trail. If true, the find*() methods will only return non-deleted rows, unless the

<?php $user = $userModel->findColumn($column_name);

4 method is called prior to calling the find*() method.

This requires either a DATETIME or INTEGER field in the database as per the model’s setting. The default field name is

<?php $user = $userModel->findColumn($column_name);

3 however this name can be configured to any name of your choice by using property.

Important

The

<?php $user = $userModel->findColumn($column_name);

3 field must be nullable.

This array should be updated with the field names that can be set during

<?php $user = $userModel->findColumn($column_name);

7,

<?php $user = $userModel->findColumn($column_name);

8, or

<?php $user = $userModel->findColumn($column_name);

9 methods. Any field names other than these will be discarded. This helps to protect against just taking input from a form and throwing it all at the model, resulting in potential mass assignment vulnerabilities.

Note

The field should never be an allowed field.

New in version 4.3.0.

Whether to allow inserting empty data. The default value is

<?php $users = $userModel->find([1, 2, 3]);

6, meaning that if you try to insert empty data, an exception with “There is no data to insert.” will raise.

You may also change this setting with the method.

$useTimestamps

This boolean value determines whether the current date is automatically added to all inserts and updates. If

<?php $users = $userModel->find([1, 2, 3]);

7, will set the current time in the format specified by . This requires that the table have columns named created_at, updated_at and deleted_at in the appropriate data type. See also , , and .

$dateFormat

This value works with and to ensure that the correct type of date value gets inserted into the database. By default, this creates DATETIME values, but valid options are:

<?php $users = $userModel->findAll();

2,

<?php $users = $userModel->findAll();

3, or

<?php $users = $userModel->findAll();

4 (a PHP timestamp). Using or with an invalid or missing will cause an exception.

$createdField

Specifies which database field to use for data record create timestamp. Set to an empty string (

<?php $users = $userModel->findAll();

  1. to avoid updating it (even if is enabled).
$updatedField

Specifies which database field should use for keep data record update timestamp. Set to an empty string (

<?php $users = $userModel->findAll();

  1. to avoid updating it (even is enabled).
$deletedField

Specifies which database field to use for soft deletions. See .

$validationRules

Contains either an array of validation rules as described in or a string containing the name of a validation group, as described in the same section. Described in more detail below.

$validationMessages

Contains an array of custom error messages that should be used during validation, as described in . Described in more detail below.

$skipValidation

Whether validation should be skipped during all inserts and updates. The default value is

<?php $users = $userModel->find([1, 2, 3]);

6, meaning that data will always attempt to be validated. This is primarily used by the

<?php $users = $userModel->findAll();

8 method, but may be changed to

<?php $users = $userModel->find([1, 2, 3]);

7 so this model will never validate.

$cleanValidationRules

Whether validation rules should be removed that do not exist in the passed data. This is used in updates. The default value is

<?php $users = $userModel->find([1, 2, 3]);

7, meaning that validation rules for the fields that are not present in the passed data will be (temporarily) removed before the validation. This is to avoid validation errors when updating only some fields.

You can also change the value by the

<?php $users = $userModel->where('active', 1)->findAll();

1 method.

Note

Prior to v4.2.7,

<?php $users = $userModel->where('active', 1)->findAll();

2 did not work due to a bug.

$allowCallbacks

Whether the callbacks defined below should be used. See .

$beforeInsert
$afterInsert
$beforeUpdate
$afterUpdate
$beforeFind
$afterFind
$beforeDelete
$afterDelete
$beforeInsertBatch
$afterInsertBatch
$beforeUpdateBatch
$afterUpdateBatch

These arrays allow you to specify callback methods that will be run on the data at the time specified in the property name. See .

Several functions are provided for doing basic CRUD work on your tables, including

<?php $users = $userModel->find([1, 2, 3]);

5,

<?php $user = $userModel->findColumn($column_name);

8,

<?php $user = $userModel->findColumn($column_name);

9,

<?php $user = $userModel->findColumn($column_name);

2 and more.

Returns a single row where the primary key matches the value passed in as the first parameter:

<?php $user = $userModel->find($user_id);

The value is returned in the format specified in .

You can specify more than one row to return by passing an array of primaryKey values instead of just one:

<?php $users = $userModel->find([1, 2, 3]);

Note

If no parameters are passed in,

<?php $users = $userModel->find([1, 2, 3]);

5 will return all rows in that model’s table, effectively acting like

<?php $users = $userModel->where('active', 1)->findAll();

8, though less explicit.

Returns null or an indexed array of column values:

<?php $user = $userModel->findColumn($column_name);

<?php $users = $userModel->where('active', 1)->findAll();

9 should be a name of single column else you will get the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

00.

Returns all results:

<?php $users = $userModel->findAll();

This query may be modified by interjecting Query Builder commands as needed prior to calling this method:

<?php $users = $userModel->where('active', 1)->findAll();

You can pass in a limit and offset values as the first and second parameters, respectively:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

0

Returns the first row in the result set. This is best used in combination with the query builder.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

1

If is true, then the find*() methods will not return any rows where

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

01. To temporarily override this, you can use the

<?php $user = $userModel->findColumn($column_name);

4 method prior to calling the find*() method.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

2

Whereas

<?php $user = $userModel->findColumn($column_name);

4 will return both deleted and not-deleted rows, this method modifies the next find*() methods to return only soft deleted rows:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

3

The first parameter is an associative array of data to create a new row of data in the database. If an object is passed instead of an array, it will attempt to convert it to an array.

The array’s keys must match the name of the columns in the , while the array’s values are the values to save for that key.

The optional second parameter is of type boolean, and if it is set to false, the method will return a boolean value, which indicates the success or failure of the query.

You can retrieve the last inserted row’s primary key using the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

04 method.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

4

New in version 4.3.0.

You can use

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

05 method to insert empty data. The Model throws an exception when you try to insert empty data by default. But if you call this method, the check will no longer be performed.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

5

You may also change this setting with the property.

You can enable the check again by calling

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

06.

Updates an existing record in the database. The first parameter is the of the record to update. An associative array of data is passed into this method as the second parameter. The array’s keys must match the name of the columns in a , while the array’s values are the values to save for that key:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

6

Important

Since v4.3.0, this method raises a

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

07 if it generates an SQL statement without a WHERE clause. In previous versions, if it is called without specified and an SQL statement was generated without a WHERE clause, the query would still execute and all records in the table would be updated.

Multiple records may be updated with a single call by passing an array of primary keys as the first parameter:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

7

When you need a more flexible solution, you can leave the parameters empty and it functions like the Query Builder’s update command, with the added benefit of validation, events, etc:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

8

This is a wrapper around the

<?php $user = $userModel->findColumn($column_name);

8 and

<?php $user = $userModel->findColumn($column_name);

9 methods that handle inserting or updating the record automatically, based on whether it finds an array key matching the primary key value:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

9

The save method also can make working with custom class result objects much simpler by recognizing a non-simple object and grabbing its public and protected values into an array, which is then passed to the appropriate insert or update method. This allows you to work with Entity classes in a very clean way. Entity classes are simple classes that represent a single instance of an object type, like a user, a blog post, job, etc. This class is responsible for maintaining the business logic surrounding the object itself, like formatting elements in a certain way, etc. They shouldn’t have any idea about how they are saved to the database. At their simplest, they might look like this:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

0

A very simple model to work with this might look like:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

1

This model works with data from the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

10 table, and returns all results as an instance of

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

11. When you need to persist that record to the database, you will need to either write custom methods, or use the model’s

<?php $user = $userModel->findColumn($column_name);

7 method to inspect the class, grab any public and private properties, and save them to the database:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

2

Note

If you find yourself working with Entities a lot, CodeIgniter provides a built-in Entity classthat provides several handy features that make developing Entities simpler.

Takes a primary key value as the first parameter and deletes the matching record from the model’s table:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

3

If the model’s value is true, this will update the row to set

<?php $user = $userModel->findColumn($column_name);

3 to the current date and time. You can force a permanent delete by setting the second parameter as true.

An array of primary keys can be passed in as the first parameter to delete multiple records at once:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

4

If no parameters are passed in, will act like the Query Builder’s delete method, requiring a where call previously:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

5

Cleans out the database table by permanently removing all rows that have ‘deleted_at IS NOT NULL’.

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

6

For many people, validating data in the model is the preferred way to ensure the data is kept to a single standard, without duplicating code. The Model class provides a way to automatically have all data validated prior to saving to the database with the

<?php $user = $userModel->findColumn($column_name);

8,

<?php $user = $userModel->findColumn($column_name);

9, or

<?php $user = $userModel->findColumn($column_name);

7 methods.

Important

When you update data, by default, the validation in the model class only validates provided fields. This is to avoid validation errors when updating only some fields.

But this means

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

17 rules do not work as expected when updating. If you want to check required fields, you can change the behavior by configuration. See for details.

The first step is to fill out the class property with the fields and rules that should be applied. If you have custom error message that you want to use, place them in the array:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

7

If you’d rather organize your rules and error messages within the Validation configuration file, you can do that and simply set to the name of the validation rule group you created:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

8

The other way to set the validation rules to fields by functions,

class CodeIgniter\Model CodeIgniter\Model::setValidationRule($field, $fieldRules)Parameters:

  • $field ( <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    }
  • $fieldRules ( <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    }

This function will set the field validation rules.

Usage example:

<?php namespace App\Models; use Modules\Authentication\Models\UserAuthModel; class UserModel extends UserAuthModel {
/**
  • Called during initialization. Appends
  • our custom field to the module's model.
     */
    protected function initialize()
    {
        $this->allowedFields[] = 'middlename';
    }
    
    }

9

CodeIgniter\Model::setValidationRules($validationRules)Parameters:

  • $validationRules ( <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    }

This function will set the validation rules.

Usage example:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

0

The other way to set the validation message to fields by functions,

CodeIgniter\Model::setValidationMessage($field, $fieldMessages)Parameters:

  • $field ( <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    }
  • $fieldMessages ( <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    }

This function will set the field wise error messages.

Usage example:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

1

CodeIgniter\Model::setValidationMessages($fieldMessages)Parameters:

  • $fieldMessages ( <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    }

This function will set the field messages.

Usage example:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

2

Now, whenever you call the

<?php $user = $userModel->findColumn($column_name);

8,

<?php $user = $userModel->findColumn($column_name);

9, or

<?php $user = $userModel->findColumn($column_name);

7 methods, the data will be validated. If it fails, the model will return boolean false.

You can use the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

27 method to retrieve the validation errors:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

3

This returns an array with the field names and their associated errors that can be used to either show all of the errors at the top of the form, or to display them individually:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

4

You can retrieve a model’s validation rules by accessing its

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

28 property:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

5

You can also retrieve just a subset of those rules by calling the accessor method directly, with options:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

6

The

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

29 parameter is an associative array with one element, whose key is either

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

30 or

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

31, and which has as its value an array of fieldnames of interest:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

7

The model provides a simple method to replace parts of your rules based on data that’s being passed into it. This sounds fairly obscure but can be especially handy with the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

32 validation rule. Placeholders are simply the name of the field (or array key) that was passed in as

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

33 surrounded by curly brackets. It will be replaced by the value of the matched incoming field. An example should clarify this:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

8

Note

Since v4.3.5, you must set the validation rules for the placeholder field (

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

34).

In this set of rules, it states that the email address should be unique in the database, except for the row that has an id matching the placeholder’s value. Assuming that the form POST data had the following:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $DBGroup = 'group_name';
}

9

then the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

35 placeholder would be replaced with the number 4, giving this revised rule:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

0

So it will ignore the row in the database that has

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

36 when it verifies the email is unique.

Note

Since v4.3.5, if the placeholder (

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

  1. value does not pass the validation, the placeholder would not be replaced.

This can also be used to create more dynamic rules at runtime, as long as you take care that any dynamic keys passed in don’t conflict with your form data.

To help protect against Mass Assignment Attacks, the Model class requires that you list all of the field names that can be changed during inserts and updates in the class property. Any data provided in addition to these will be removed prior to hitting the database. This is great for ensuring that timestamps, or primary keys do not get changed.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

1

Occasionally, you will find times where you need to be able to change these elements. This is often during testing, migrations, or seeds. In these cases, you can turn the protection on or off:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

2

You can specify the format that data should be returned as when using the find*() methods as the class property, . There may be times that you would like the data back in a different format, though. The Model provides methods that allow you to do just that.

Note

These methods only change the return type for the next find*() method call. After that, it is reset to its default value.

Returns data from the next find*() method as associative arrays:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

3

Returns data from the next find*() method as standard objects or custom class instances:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

4

Sometimes, you need to process large amounts of data and would run the risk of running out of memory. To make this simpler, you may use the chunk() method to get smaller chunks of data that you can then do your work on. The first parameter is the number of rows to retrieve in a single chunk. The second parameter is a Closure that will be called for each row of data.

This is best used during cronjobs, data exports, or other large tasks.

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

5

CodeIgniter Model has one instance of the Query Builder for that model’s database connection. You can get access to the shared instance of the Query Builder any time you need it:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

6

This builder is already set up with the model’s .

Note

Once you get the Query Builder instance, you can call methods of theQuery Builder. However, since Query Builder is not a Model, you cannot call methods of the Model.

If you need access to another table, you can get another instance of the Query Builder. Pass the table name in as a parameter, but be aware that this will not return a shared instance:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

7

You can also use Query Builder methods and the Model’s CRUD methods in the same chained call, allowing for very elegant use:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

8

In this case, it operates on the shared instance of the Query Builder held by the model.

Important

The Model does not provide a perfect interface to the Query Builder. The Model and the Query Builder are separate classes with different purposes. They should not be expected to return the same data.

If the Query Builder returns a result, it is returned as is. In that case, the result may be different from the one returned by the model’s method and may not be what was expected. The model’s events are not triggered.

To prevent unexpected behavior, do not use Query Builder methods that return results and specify the model’s method at the end of the method chaining.

Note

You can also access the model’s database connection seamlessly:

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

protected $table      = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType     = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['name', 'email'];
protected bool $allowEmptyInserts = false;
// Dates
protected $useTimestamps = false;
protected $dateFormat    = 'datetime';
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';
// Validation
protected $validationRules      = [];
protected $validationMessages   = [];
protected $skipValidation       = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert   = [];
protected $afterInsert    = [];
protected $beforeUpdate   = [];
protected $afterUpdate    = [];
protected $beforeFind     = [];
protected $afterFind      = [];
protected $beforeDelete   = [];
protected $afterDelete    = [];
}

9

There are several points within the model’s execution that you can specify multiple callback methods to run. These methods can be used to normalize data, hash passwords, save related entities, and much more.

The following points in the model’s execution can be affected, each through a class property:

  • ,
  • ,
  • ,
  • ,
  • ,
  • ,

Note

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

38,

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

39,

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

40 and

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

41 can be used since v4.3.0.

You specify the callbacks by first creating a new class method in your model to use.

This class method will always receive a

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

33 array as its only parameter.

The exact contents of the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

33 array will vary between events, but will always contain a key named

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

44 that contains the primary data passed to the original method. In the case of the insert*() or update*() methods, that will be the key/value pairs that are being inserted into the database. The main

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

33 array will also contain the other values passed to the method, and be detailed in .

The callback method must return the original

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

33 array so other callbacks have the full information.

<?php $user = $userModel->find($user_id);

0

You specify when to run the callbacks by adding the method name to the appropriate class property (, , etc). Multiple callbacks can be added to a single event and they will be processed one after the other. You can use the same callback in multiple events:

<?php $user = $userModel->find($user_id);

1

Additionally, each model may allow (default) or deny callbacks class-wide by setting its property:

<?php $user = $userModel->find($user_id);

2

You may also change this setting temporarily for a single model call using the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

47 method:

<?php $user = $userModel->find($user_id);

3

Since the exact data passed to each callback varies a bit, here are the details on what is in the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

33 parameter passed to each event:

Event

$data contents

beforeInsert

data = the key/value pairs that are being inserted. If an object or Entity class is passed to the

<?php $user = $userModel->findColumn($column_name);

8 method, it is first converted to an array.

afterInsert

id = the primary key of the new row, or 0 on failure. data = the key/value pairs being inserted. result = the results of the

<?php $user = $userModel->findColumn($column_name);

8 method used through the Query Builder.

beforeUpdate

id = the array of primary keys of the rows being updated. data = the key/value pairs that are being updated. If an object or Entity class is passed to the

<?php $user = $userModel->findColumn($column_name);

9 method, it is first converted to an array.

afterUpdate

id = the array of primary keys of the rows being updated. data = the key/value pairs being updated. result = the results of the

<?php $user = $userModel->findColumn($column_name);

9 method used through the Query Builder.

beforeFind

The name of the calling method, whether a singleton was requested, and these additional fields:

  • <?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {
    // ...  
    
    } 53

No additional fields

  • <?php $users = $userModel->find([1, 2, 3]); 5

id = the primary key of the row being searched for.

  • <?php $users = $userModel->where('active', 1)->findAll(); 8

limit = the number of rows to find. offset = the number of rows to skip during the search.

afterFind

Same as beforeFind but including the resulting row(s) of data, or null if no result found.

beforeDelete

id = primary key of row being passed to the

<?php $user = $userModel->findColumn($column_name);

2 method. purge = boolean whether soft-delete rows should be hard deleted.

afterDelete

id = primary key of row being passed to the

<?php $user = $userModel->findColumn($column_name);

2 method. purge = boolean whether soft-delete rows should be hard deleted. result = the result of the

<?php $user = $userModel->findColumn($column_name);

2 call on the Query Builder. data = unused.

beforeInsertBatch

data = associative array of values that are being inserted. If an object or Entity class is passed to the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

59 method, it is first converted to an array.

afterInsertBatch

data = the associative array of values being inserted. result = the results of the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

60 method used through the Query Builder.

beforeUpdateBatch

data = associative array of values that are being updated. If an object or Entity class is passed to the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

61 method, it is first converted to an array.

afterUpdateBatch

data = the key/value pairs being updated. result = the results of the

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

61 method used through the Query Builder.

The

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

63 and

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

64 methods can both return a modified set of data to override the normal response from the model. For

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

64 any changes made to

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

44 in the return array will automatically be passed back to the calling context. In order for

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

63 to intercept the find workflow it must also return an additional boolean,

<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model {

// ...
}

68:

<?php $user = $userModel->find($user_id);

4

You do not need to extend any special class to create a model for your application. All you need is to get an instance of the database connection and you’re good to go. This allows you to bypass the features CodeIgniter’s Model gives you out of the box, and create a fully custom experience.

How to delete data from database in CodeIgniter?

CodeIgniter Delete Data From Database.

VIEW FILE: delete_view.php. In this, we fetched all the names from data base and showed them in links. ... .

CONTROLLER FILE: delete_ctrl.php. copy the below file in your controller directory. ... .

MODEL FILE: delete_model.php. ... .

My SQL Code Segment: ... .

CSS FILE: delete.css..

How do I delete the first 3 rows in SQL?

If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

How do I delete the last record in SQL?

The Syntax for Using the SQL Delete Command.

The table from which we want to delete rows is specified in the table_name parameter of the DELETE FROM statement..

There is an optional WHERE clause in which we can specify the condition according to which the rows should get deleted..

How to use where in CodeIgniter 3?

You can use the where method multiple times to build up a WHERE clause with multiple AND clauses. The or_where method can be used to add OR clauses to the WHERE clause.