codeigniter
  1. codeigniter-models

Models in CodeIgniter

In CodeIgniter, Models are used to interact with databases. Models represent data that is being transferred between the application and database. Models contain methods that help to get, insert, update and delete data from tables.

Syntax

To create a Model in CodeIgniter, follow the syntax below:

class Model_name extends CI_Model {
    public function __construct() {
        parent::__construct();
        $this->load->database();
    }
 
    function get_data($data) {
        $this->db->select('*');
        $this->db->from('table_name');
        $this->db->where('column', $data);
        $query = $this->db->get();
        return $query->result();
    }
}

Example

Let’s consider a simple example. Create a model file, “User_model.php” in “application/models/” directory. Add the below code in the file.

class User_model extends CI_Model {

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function insert_user($data) {

        $this->db->insert('users', $data);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}

Explanation

In the above model, we have created a method “insert_user”. It will insert a record of a user. It takes an array of user information as a parameter. The method then inserts the data into the users table. The “$this->db->affected_rows() ” method will check whether any data was inserted or not.

Use

The model is used to retrieve data from the database and to interact with controllers. Models act as data interfaces, and they control database interactions via methods.

Important Points

  • In CodeIgniter, Models represent data that is being transferred between the application and database.
  • Models contain methods to get, insert, update and delete data from tables.
  • All the models should extend CI_Model.
  • The name of a model file must always start with a capital letter.
  • A model can be loaded using the load->model() function of CodeIgniter.

Summary

In CodeIgniter, Models represent data that is being transferred between the application and database. Models contain methods to get, insert, update and delete data from tables. All models should extend CI_Model. Model files should have a capital first letter, and can be loaded using the load->model() function.

Published on: