How to create models in codeigniter?
What is model in codeigniter?
What is model ?
How to create model in codeigniter
why use model in codeigniter?
Model is a php class which perform Create, Read, Update, Delete (CRUD) action in database.
In Codeigniter application we need to call a function to get data from the database. Model id responsible for handle all data logic and load data in the view page. model is stored in application/models directory(folder).
The first letter of model class is always Capital letter.
Example :-
File Name : Common_model.php
defined('BASEPATH') OR exit('no direct script access allowed');
class Common_model extends CI_Model
{
var $title = '';
var $name = '';
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function categorylist()
{
$this->db->select('*');
$this->db->from('categories');
$this->db->where('parent_id','0');
$query=$this->db->get();
$result = $query->result();
if(!empty($result)){
return $result;
}
else{
return false;
}
}
public function get_last_ten_record()
{
$qry = $this->db->get('tutorial', 10);
return $qry->result();
}
}
Load Database :-
You can load database and model anywhere in your controller class. and you can also set auto load file in config directory.
File Name :
$this->load->database();
How to load model class ?
you can load model in three ways:
1. Load in constructor method.
2. Load in Methods.
3. Auto Load config file.
File Name :
$this->load->model('model_name');
Where model_name is the name of the model to be loaded. After loading the model you can simply call its method as shown below.
$this->load->model('Common_model');
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model('blog/user_model');
class Ittutorial extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('My_model');
}
public function index()
{
$data = array();
$data['title'] = "Home";
$data['category'] = $this->My_model->categorylist();
$data['subcategory'] = $this->My_model->subcategorylist();
$this->load->view('header',$data);
$this->load->view('home');
$this->load->view('footer');
}
}
Auto-loading Models
If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload.php file and adding the model to the autoload array.
$autoload['model'] = array('Auth_model');
// $autoload['model'] = array('first_model', 'second_model');
how to connect to Database
When a model is loaded it does NOT connect automatically to your database.
There are two ways to connect to a database:
Automatically Connecting
Manually Connecting
Automatically Connecting
Manually Connecting
Automatically Connecting
Auto-connect feature will automatically load your database with every page load. To enable it, add 'database' in the array library in autoload.php file.
$autoload['libraries'] = array('database');
Manually Connecting
If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
Example
class Blog_model extends CI_Model {
public $title;
public $content;
public $date;
public function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
public function insert_entry()
{
$this->title = $_POST['title']; // please read the below note
$this->content = $_POST['content'];
$this->date = time();
$this->db->insert('entries', $this);
}
public function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
}
How To use(Connect) Multiple Database In CodeIgniter
Generally, one database is used for a single web application. But sometimes we need to use two or more database in a single site.
CodeIgniter provides an easy way to connect and use multiple database on the same or different server.
Configuration of Multiple Database
Open the application/config/database.php
//Default database configuration
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'db_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
//Another database configuration
$db['another_db'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'db_username2',
'password' => 'db_password2',
'database' => 'db_name2',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
You can Use Multiple Database In CodeIgniter
Now you can access multiple database connections by the database object.
File name : Auth_model.php
//Load another database
$DB2 = $this->load->database('another_db', TRUE);
Set the second parameter to TRUE to get the database object.
//Default database query
$this->db->select('first_name, last_name');
$this->db->from('users');
$this->db->where('id', 99);
$query = $this->db->get();
//Another database query
$DB2->select('image');
$DB2->from('cdn_images');
$DB2->where('id', 25);
$query = $DB2->get();
Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main_model extends CI_Model {
function getRecords(){
// Load database
$db2 = $this->load->database('database2', TRUE);
// Select records from 1st database
$this->db->select('*');
$q = $this->db->get('users');
$result1 = $q->result_array();
// Select records from 2nd database
$db2->select('*');
$q = $db2->get('students');
$result2 = $q->result_array();
$response = array("response1"=>$result1,"response2"=>$result2);
return $response;
}
}
Previous
Next