First, create a model (project directory models). Note: The model name is the same as the file name and must inherit the data core class CI_Model, And the constructor in the parent class must be reloaded. CodeIgniter's data function class is in \ system \ database \ DB_active_rec.php
The Code is as follows:
Class ModelName extends CI_Model
{
Function _ construct ()
{
Parent: :__ construct ();
}
}
Connect to the database: $ this-> load-> database ();
The Code is as follows:
ClassModel_name extends CI_Model
{
Function _ construct ()
{
Parent: :__ construct ();
$ This-> load-> database ();
}
}
Written in the model constructor, so that the model can be loaded and connected to the database, which is very convenient.
Insert data
The Code is as follows:
$ This-> db-> insert ($ tableName, $ data );
$ TableName = indicates the name of the table to be operated.
$ Data = the data you want to insert, which is inserted as an array (key name = field name, key value = field value, auto-incrementing primary key does not need to be written ).
Update Data
The Code is as follows:
$ This-> db-> where ('field name', 'field value ');
$ This-> db-> update ('table name', an array of modified values );
Query data
The Code is as follows:
$ This-> db-> where ('field name', 'field value ');
$ This-> db-> select ('field ');
$ Query = $ this-> db-> get ('table name ');
Return $ query-> result ();
Delete data
The Code is as follows:
$ This-> db-> where ('field name', 'field value ');
$ This-> db-> delete ('table name ');
Next, we need to call our model in the controller.
The Code is as follows:
$ This-> load-> model ('model name') // Model name refers to the model you created under the project directory/models/(same as the file name)
$ This-> model name-> method name
To avoid calling each controller method once. I did this.
The Code is as follows:
Class ControllerName extends CI_Controller
{
Function _ construct ()
{
Parent: :__ construct ();
$ This-> load-> model ('model name ');
}
}