Web Programming TutorialsModels in CodeIgniter PART-1

Models in CodeIgniter PART-1

We saw controllers and views in codeigniter, now we will try to deal with databases. Models are used in Codeigniter to perform database operations. So let us learn about it in this Models in CodeIgniter tutorial.

    • What is a Model:
      • A model is a PHP class which is designed to work with information in your database.
      • Instead of performing database operations in controller you can write queries and perform various database operations in the model class and then call it in controller.
      • This will allow you to reuse the class performing database operations later when required.
      • The model class file is to be created in the application/models folder which is in the CodeIgniter folder inside your server folder.
      • You can even create a new folder inside the application/models folder and save your file in that folder.
      • The model class inherits from its base class CI_Model just as controller inherits from its base class CI_Controller.
      • According to the naming convention the name of the model class should start with initial capital letter with rest of the letters in small case.
      • The example of model class is shown below:
<?php
class Book_model extends CI_Model
{
	function __contruct()
	{
		parent::__construct();
	}
}
?>
      • The file name that contains the model class should have the same name as model class with all letters in small case. This will help in remembering the names of the file and class both.
      • All the operations with the database are to be performed in the model class itself by creating functions for different operations.
      • Use of Active Record: To perform operations on database, codeigniter uses a database abstraction layer known as Active Record. It is a pattern which allows information to be inserted, retrieved and updated in our database with minimum scripting.
      • Some of the operations using Active Record functions are shown below (consider book as a table in the database):
        1. $this->db->get():
          • It runs the select query and gives result. It can be used to retrieve all the rows from a table in the database.
          • Example:
$query-$this->db->get(‘book’);
          • It performs “select * from book;” operation.
        1. $this->db->get_where():
          • It allows you to add a where clause to your select query.
          • Example:
$id=101;
$query=$this->db->get_where(‘book’,array(‘id’=>$id));
          • This will perform “select * from book where id = $id;” operation.
        1. $this->db->distinct():
          • This function will add Distinct keyword to the query.
          • Example:
$this->db->distinct();
$this->db->get(‘book’);
          • This will perform “select DISTINCT * from book;” operation.
        1. $this->db->count_all()
          • It allows you to count all the rows present in the table.
          • Example:
echo $this->db->count_all(‘book’);
          • It will display the number of rows in book table for example : 10.
        1. $this->db->insert():
          • It generates an insert query on the basis of the data you supply.
          • We can supply data in the form of an array or an object.
          • Example:
$data=array(‘title’=>’You Can WIN’,’author’=>’Shiv Khera’,’price’=>200);
$this->db->insert(‘book’,$data);
          • This will perform “INSERT INTO book (title,author,price) values(‘You Can Win’,’Shiv Khera’,200);” operation.
        1. $this->db->update():
          • It generates an update query according to the data passed and executes it.
          • You can pass data in the form of an array or an object.
          • Example:
$id=100;
$data=array(‘title’=>’You Can WIN’,’author’=>’Shiv Khera’,’price’=>250);
$this->db->where(‘id’=>$id);
$this->db->update(‘book’,$data);
          • This will perform “update book set ‘title’=’{$title}’, ‘author’=’{author}’, ‘price’={price} where ‘id’=$id;” operation.
        1. $this->db->delete():
          • It generates a delete SQL string and runs the query.
          • Example:
$this->db->delete(‘book’,array(‘id’=>$id));
          • It will perform “DELETE from book WHERE id = $id;” operation.
      • These were some of the operations which can be used in the model class to perform required operations.
      • Loading of the model in the controller: Next when the model class is ready, it needs to be loaded in the controller just like views for using the database.
      • The built-in Loader class provides the function to load the model class in the controller.
      • The function used for loading model class is given below:
$this->load->model(‘Model_name’);
      • The $this->load->model() function is used to load the required model. The parameter Model_name inside the function call indicates the name of the file in which the model class is defined.
      • This applies only when you have saved your model class file directly in the application/models folder.
      • If you have stored your model class file in a newly created folder inside the application/models folder, you will have to specify its relative path i.e. path following the models folder.
      • For example: you have created a folder named books_db in the application/models folder and stored your model class file named book_model inside it, its path can be specified as shown below:
$this->load->model(‘books_db/book_model’);
      • No need to specify the extension of the file since it is .php only.
      • To use the functions defined inside the model class you can use the model_name itself as the object.
      • I mean if you have book_model as your model name and save() is the function defined in your model class, you can call it as shown below:
$this->book_model->save();
      • Specifying another object name instead of using model class file name as object: If you want some other name for your object instead of using the model name itself you can specify it at the time of loading the model as shown below:
      • Consider book_model as your model name:
$this->load->model(‘book_model’,’Book’);
      • Now instead of using book_model as object name you can use Book as object of the model class to call the class members and functions.
      • Now the save() method previously talked about can be called as follows:
$this->Book->save();
      • Auto-loading your model: If you feel the need that your model should be global in your application, you can tell this to codeigniter to auto-load your model during system initialization. This can be done by opening the application/config/autoload.php file and assigning the model class file name to the autoload array for models.
      • It is shown below:
$autoload['model'] = array('book_model');
      • Here note that the model class file name without its extension is specified in the array.
      • Connecting to the database: When the model class is loaded in the controller it does not connect to the database. You need to follow some steps to connect it with database.
      • You can use two methods to connect the database with the model class 1.) Automatically connecting 2.) Manually connecting.
      • Automatically Connecting: The auto-load feature will load and instantiate the database class with every page load.
      • To automatically connect to the database you need to provide the connectivity settings in the database.php file which is located in the application/config folder.
      • The file is shown below:

fig 1

      • The database file connects to mysql by default. If you want to use any other database you can specify it by replacing mysql with its name. You are expected to provide your username, password and database name in this file.
      • Then to enable the “auto-load” feature open the application/config/autoload.php file and add the word database to the library array as shown below:
$autoload['libraries'] = array('database');
      • OR instead of adding it to library array in autoload.php file you enable autoloading by specifying the third parameter as TRUE in the function loading the model as shown below:
$this->load->model(‘book_model’,’’,TRUE);
      • Manually connecting: If only some of your pages require database connection, you can add the following statement to the function that accesses database or to the constructor so that it is available to all the functions in the class. The statement is as follows:
$this->load->database();
      • This function consists of three parameters, but if it is empty it will connect to the database group specified in the database.php file in the application/config folder.
      • I mean we can specify our username, password and database name in the database.php file which is in application/config folder and then add the statement $this->load->databse(); in the pages that require database connection.
      • In this situation the connections specified in the database.php file will be used in our application pages.
      • OR other way is specifying the connection settings in an array or a DSN and passing that array or DSN in the function for loading database.
      • Let us first go through the parameters accepted by $this->load->database(); function.
      • Parameter 1: the database connection values passed either as an array or a DSN.
      • Parameter 2: TRUE/FALSE (Boolean value): This parameter if set to TRUE returns connection ID (This is used when we connect to multiple databases).
      • Parameter 3: TRUE/FALSE (Boolean value): Whether to enable to Active Record class. It is set to TRUE by default enabling the active record class.
      • Now if we have not specified the connection setting values in the database.php file as stated above we can collect them in an array as pass that array in the $this->load->database() function as shown below:
$config['hostname'] = "localhost";
$config['username'] = "your_db_username";
$config['password'] = "your_db_password";
$config['database'] = "your_database_name";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";

$this->load->database($config);
      • Here, the $config is the array name. In the above array value you can replace your_db_username, your_db_password and your_database_name with whatever username, pwd and database name you have for your database.
      • This $config array is passed as the first parameter to your $this->load->database() function.
      • Instead of passing array as the first parameter to the $this->load->database() function you can even pass the DSN as shown below:
$dsn = 'dbdriver://username:password@hostname/database';
$this->load->database($dsn);
    • The dsn is contains the username, password, hostname and database name of your database.

 

Thus we learned theoretically what models are and how to work with models in codeigniter in this Models in CodeIgniter PART-1; we will try them practically in the next tutorial.

1 COMMENT

  1. db->insert($table, $data);
    if($flag)
    {
    return $this->db->insert_id();
    }
    else
    {
    return false;
    }
    }

    function get_single($table, $filter)
    {
    $data = $this->db->get_where($table, $filter);
    if($data->num_rows() > 0)
    {
    $data = $data->first_row(“array”);
    return $data;
    }
    else
    {
    return false;
    }
    }

    function get_by_condition($table, $filter)
    {
    $data = $this->db->get_where($table, $filter);
    if($data->num_rows() > 0)
    {
    $data = $data->result_array();

    return $data;
    }
    else
    {
    return false;
    }
    }

    function get_all($table, $order_by=”id”, $order=”ASC”)
    {
    $this->db->order_by($order_by, $order);
    $data = $this->db->get($table);
    if($data->num_rows() > 0)
    {
    $data = $data->result_array();
    return $data;
    }
    else
    {
    return false;
    }
    }

    function update_data($table, $data, $filter)
    {
    $this->db->where($filter);
    $flag = $this->db->update($table, $data);
    if($flag)
    {
    return true;
    }
    else
    {
    return false;
    }
    }

    function delete_data($table, $filter)
    {
    $this->db->where($filter);
    $flag = $this->db->delete($table);
    return $flag;
    }

    function randomstring($length = 6)
    {
    $characters = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
    $charactersLength = strlen($characters);
    $randomString = ”;
    for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength – 1)];
    }
    return $randomString;
    }

    function delete_multiple($table, $records = "")
    {
    $flag = false;
    if($records != "")
    {
    if(is_array($records))
    {
    for($i = 0;$i $records[$i]);
    $flag = $this->delete_data($table, $filter);
    if($flag)
    {
    if($table == ‘users’)
    {
    $extra_userata = array(‘userid’ => $records[$i]);
    $this->delete_data(“personal_information”, $filter);
    $this->delete_data(“employ_information”, $filter);
    $this->delete_data(“applications”, $filter);
    $this->delete_data(“education_details”, $filter);
    }

    $total = $i + 1;
    $flag = $total;
    }
    else
    {
    $flag = false; break;
    }
    }
    }
    else
    {
    $filter = array(“id” => $records);
    $flag = $this->delete_data($table, $filter);
    }
    }
    return $flag;
    }

    function send_mail2($subject = “testing”, $content = “testing”, $email = “”)
    {
    $flag = false;
    if($email != “”)
    {
    $config[‘charset’] = ‘iso-8859-1’;
    $config[‘wordwrap’] = TRUE;
    $config[‘mailtype’] = “html”;

    $this->email->initialize($config);
    $this->email->to($email);
    $this->email->from(‘[email protected]’);

    $this->email->subject($subject);
    $this->email->message($content);
    $flag = $this->email->send();
    }
    return $flag;
    }

    function fileupload($path = “upload”, $types = “”, $input = “”)
    {
    $config[‘upload_path’] = ‘./’.$path.’/’;
    $config[‘allowed_types’] = $types;
    $config[‘max_size’] = 2048;
    $config[‘file_name’] = date(‘YmdHis’);
    $this->load->library(‘upload’, $config);

    if($this->upload->do_upload($input))
    {
    $uploaddata = $this->upload->data();
    $this->load->library(‘image_lib’);
    $img_thumb = array(
    ‘image_library’ => ‘gd2’,
    ‘source_image’ => $uploaddata [‘full_path’],
    ‘new_image’ => $uploaddata [‘file_path’].”thumbs”,
    ‘maintain_ratio’ => TRUE,
    ‘create_thumb’ => TRUE,
    ‘thumb_marker’ => “”,
    ‘width’ => 60,
    ‘height’ => 60
    );

    $this->image_lib->initialize($img_thumb);
    if(!$this->image_lib->resize())
    {
    $error = $this->image_lib->display_errors();
    print_r($error);
    }
    $this->image_lib->clear();
    $view_thumb = array(
    ‘image_library’ => ‘gd2’,
    ‘source_image’ => $uploaddata [‘full_path’],
    ‘new_image’ => $uploaddata [‘file_path’].”view_img”,
    ‘maintain_ratio’ => TRUE,
    ‘create_thumb’ => TRUE,
    ‘thumb_marker’ => “”,
    ‘width’ => 200,
    ‘height’ => 200
    );
    $this->image_lib->initialize($view_thumb);
    if(!$this->image_lib->resize())
    {
    $error = $this->image_lib->display_errors();
    print_r($error);
    }
    else
    {
    return $uploaddata[‘orig_name’];
    }
    }
    else
    {
    $error = $this->upload->display_errors();
    print_r($error);
    }
    return false;
    }

    function create_log($user = ”, $log = ”)
    {
    $data = array(‘userid’ => $user, ‘log’ => $log);
    $table = ‘logs’;
    $flag = $this->insert_data($table, $data);
    return $flag;
    }

    function get_export_users($job = “”)
    {
    $this->db->select(‘US.id as uid, US.created as ucreated, US.*, AP.*, JB.*’, ‘DT.*’, ‘SQ.*’);
    $this->db->from(‘users as US’);
    $this->db->join(‘applications as AP’, ‘AP.userid = US.id’);
    $this->db->join(‘jobs as JB’, ‘JB.id = AP.jobid’);

    if($job != “” && $job != NULL)
    {
    $this->db->where(‘AP.jobid’, $job);
    }
    $data = $this->db->get();
    if($data->num_rows() > 0)
    {
    return $data->result_array();
    }
    else
    {
    return false;
    }
    }

    function send_mail($to, $from, $name, $subject, $msg = “”)
    {
    $config[‘protocol’] = ‘sendmail’;
    $config[‘mailpath’] = ‘/usr/sbin/sendmail’;
    $config[‘charset’] = ‘iso-8859-1’;
    $config[‘wordwrap’] = TRUE;
    $config[‘mailtype’] = ‘html’;
    $this->email->initialize($config);

    $this->email->to($from);
    $this->email->from($to, $name);
    $this->email->subject($subject);

    $msg_header = “”;
    $msg_footer = “”;

    $msg = $msg_header.$msg;
    $msg .= $msg_footer;

    $this->email->message($msg);

    $flag = $this->email->send();

    return $flag;
    }

    function count_new_users()
    {
    $this->db->select(“US.id AS uid, US.*, JE.*, JB.*”);
    $this->db->from(“users AS US”);
    $this->db->join(“employ_information AS JE”, “US.id = JE.userid”);
    $this->db->join(“applications AS AP”, “AP.userid = US.id”);
    $this->db->join(“jobs AS JB”, “AP.jobid= JB.id”);

    $this->db->where(“US.new_user”, 1);
    $data = $this->db->get();
    if($data->num_rows() > 0 )
    {
    return $data->result_array();
    }
    else
    {
    return false;
    }
    }

    function get_templete($tempate_for = “”)
    {
    if($tempate_for != “”)
    {
    $filter = array(“mail_for” => $tempate_for);
    $table = “mail_templates”;
    $data = $this->get_single($table, $filter);

    if($data != false)
    {
    $template = $data[‘template’];
    return $template;
    }
    else
    {
    return false;
    }
    }
    else
    {
    return false;
    }
    }

    public function notification($slug = “”)
    {
    $msg = “”;
    if($slug != “”)
    {
    $filter = array(“msg_slug” => $slug);
    $table = “notifications”;
    $data = $this->get_single($table, $filter);
    if($data != false)
    {
    $msg = $data[‘message’];
    }

    }
    return $msg;
    }

    function age($date)
    {
    $today = date(‘d-m-Y’);
    $date1 = date_create($today);
    $date2 = date_create($date);
    $diff = date_diff($date1,$date2);
    return $diff->y;
    }

    }
    ?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -