Model

Models are PHP classes that are designed to work with information in your database. The class model contains functions to insert, update, delete, and retrieve from your database. Just think that a model contains the main logic of your application.

For the sake of this topic, we'll be using the database structure below. You can also import this database into your localhost using shop.sql. This database is named "shop".


Connecting to Your Database

In order to run queries, we have to connect CI to the MySQL Server and select the database to be used. This is done by updating /application/config/database.php:

$db['default']['hostname'] = 'localhost'; 
$db['default']['username'] = 'root';
$db['default']['password'] = 'root'; //use '' if you're using WAMP
$db['default']['database'] = 'shop';

Reminder: If you are using WAMP, the default password is "", if you are going to put your site online, the hostname is usually the IP address of your server or your website's domain name.


Anatomy of a Model

Model classes represent the tables in a database. Whenever you create a model class, it should extend the CI_Model class from CodeIgniter, hence, establishing inheritance where our new model inherits certain methods and attributes from the parent class.

Let's copy the codes below and save it as manufacturer.php. The file path should be application/models/Manufacturer.php.

class Manufacturer extends CI_Model {
     function get_all_manufacturers()
     {
         return $this->db->query("SELECT * FROM Manufacturers")->result_array();
     }
     function get_manufacturer_by_id($manufacturer_id)
     {
         return $this->db->query("SELECT * FROM Manufacturers WHERE id = ?", array($manufacturer_id))->row_array();
     }
     function add_manufacturer($manufacturer)
     {
         $query = "INSERT INTO Manufacturers(name, created_at, updated_at) VALUES (?,?,?)";
         $values = array($manufacturer['name'], date("Y-m-d, H:i:s"), date("Y-m-d, H:i:s")); 
         return $this->db->query($query, $values);
     }
}

Here, we have three methods defined in the model: one to retrieve all manufacturers, one to get a manufacturer with a particular id, and one to add a manufacturer. You may also notice that we have used built-in functions:

$this->db->query() - this literally lets us specify the full query string.
result_array() - this method runs our query and returns all results in a multi-dimensional array.
row_array() - this method runs our query and returns the first row only in a simple array.

Aside from that, observe how we used the "?" (query binding) as a substitute for real values. It's important to know that this ESCAPES properly our value/s to av...