MacBook avec code sur un bureau

PHP – CodeIgniter how to create and use a model

Looking at the structure of CodeIgniter we see that there is a folder called application/models. It is in this one that we will create our model.

For a model to be usable as such, it must extend CI_Model.

class ScoresModel extends CI_Model {
   function __construct(){
      // Call the Model constructor
      parent::__construct();
      $this->load->database();
   }
   function getAllScores(){
      $query = $this->db->query('SELECT * FROM scores');
      return $query->result_array();
   }
}

For it to be accessible in the controller you have to start by loading it

$this->load->model('scoresmodel');

then just call the desired method

$this->scoresmodel->saveScore($userid,$gameid,$score,$timestamp);