[PHP] CodeIgniter learning Manual (III): Model introduction and simple cases

Source: Internet
Author: User
What is a model? A model is a PHP class specifically used to deal with databases. For example, suppose you want to use CodeIgniter to create a Blog. You can write a model class that contains methods for inserting, updating, and deleting Blog data. The following example shows you a common model class :? ClassBlogmodelextendsCI_Model {var $ title

What is a model? A model is a PHP class specifically used to deal with databases. For example, suppose you want to use CodeIgniter to create a Blog. You can write a model class that contains methods for inserting, updating, and deleting Blog data. The following example shows you a common model class :? Class Blogmodel extends CI_Model {var $ title ='

What is a model?

A model is a PHP class specifically used to deal with databases. For example, suppose you want to use CodeIgniter to create a Blog. You can write a model class that contains methods for inserting, updating, and deleting Blog data.

The following example shows you a common model class:

 Db-> get ('entries', 10); return $ query-> result ();} function insert_entry () {$ this-> title =$ _ POST ['title']; // read the remarks below $ this-> content =$ _ POST ['content']; $ this-> date = time (); $ this-> db-> insert ('entries', $ this);} function update_entry () {$ this-> title =$ _ POST ['title']; $ this-> content =$ _ POST ['content']; $ this-> date = time (); $ this-> db-> update ('entries', $ this, array ('id' = >$ _ POST ['id']);} }?>

Note: The above function is an Active Record database function.

Note: For simplicity, $ _ POST is directly used.

However, this is not very good. We should usually use the following types:

$this->input->post('title');


Profiling Model

Model files are stored in the application/models/folder. If you want to, you can create a subfolder in it.
The most basic model class must be like this:
class Model_name extends CI_Model {    function __construct()    {        parent::__construct();    }}

Model_name is the name of the model class. The first letter of the class name must be in upper case, and the other letters must be in lower case. Make sure that your Class inherits the Base Model Class ).


The file name must be a lower-case version of the model class name. For example, if your class is:
class User_model extends CI_Model {    function __construct()    {        parent::__construct();    }}
The class file name should be:

Application/models/user_model.php


Load Model
The model can be referenced in the controller. Like this:
$this->load->model('Model_name');

If the model file is in a subfolder, a relative path name is required for reference. For example, if you have a model application/models/blog/queries. php. The following code can reference it:
$this->load->model('blog/queries');

Once a model is loaded, you can use the following method:
$this->load->model('Model_name');$this->Model_name->function();

By default, the model name is directly introduced as the object name, as shown above. Of course, if you want to, you can get a better object name! You can specify the second parameter in the model loading function. For example:
$this->load->model('Model_name', 'fubar');$this->fubar->function();

Here is an example of a controller. Load a model and display it in the view.
class Blog_controller extends CI_Controller {    function blog()    {        $this->load->model('Blog');        $data['query'] = $this->Blog->get_last_ten_entries();        $this->load->view('blog', $data);    }}

Automatic model Loading
If you need a specific model that works throughout the project, you can have CodeIgniter automatically load it during initialization. The method is to open the application/config/autoload. php file and add the model to the automatically loaded array.

Note: After testing (taking loading a model as an example), the memory consumption is the same when the model is automatically loaded and manually loaded.

However, the larger the load model, the larger the memory consumption. The Automatic Loading Model sacrifices the memory consumption, so try not to automatically load the model that does not need to run through the whole site project!


Connect to database

When a model is loaded, it does not automatically connect to the database. You can connect to the database using the following methods:
You can use the standard method to connect to the database (description), or through the Controller or your custom model.
You can set the third parameter to TRUE to enable the model Loading Function to automatically connect to the database. The connection configuration can be defined in your database configuration file:
    $this->load->model('Model_name', '', TRUE);

You can manually set the third parameter to load your custom Database Configuration:

$config['hostname'] = "localhost";$config['username'] = "myusername";$config['password'] = "mypassword";$config['database'] = "mydatabase";$config['dbdriver'] = "mysql";$config['dbprefix'] = "";$config['pconnect'] = FALSE;$config['db_debug'] = TRUE;$this->load->model('Model_name', '', $config);

The following is the Model I used to connect to the database in SAE. It encapsulates some common methods, such as Select and Insert.

 Mysql = new SaeMysql ();}/* Select query function of MySQL. The function parameters are as follows: * 1. table Name-2. column name-3. the number of rows starting with-4. the queried function */function select_limit ($ table_name, $ row_name, $ start_row, $ row_count) {$ this-> SQL = "SELECT ". $ row_name. "FROM "'. $ table_name. "'limit ". $ start_row. ",". $ row_count. ""; $ data = $ this-> mysql-> getData ($ this-> SQL); return $ data;}/* Select query function of MySQL, the function parameters are as follows: * 1. table Name-2. column name-3. column name queried-4. target */function select_where ($ table_name, $ ro W_name, $ where_row, $ target_row) {$ this-> SQL = "SELECT ". $ row_name. "FROM "'. $ table_name. "'where "'. $ where_row. "'= ". $ target_row; $ data = $ this-> mysql-> getData ($ this-> SQL); return $ data;}/* Insert function of MySQL, the function parameters are as follows: * 1. table Name-2. insert an associated array */function insert_into ($ table_name, $ array_data) {// $ tempKey and $ tempValue temporarily store the inserted data $ temp_key_string = ""; $ temp_value_string = ""; // retrieve and store the data from the associated array in the string foreach ($ array_d Ata as $ key => $ value) {$ temp_key_string. = ""'. $ key. "',"; $ temp_value_string. = "'". $ value. "',";} // remove the end comma $ temp_key_string = substr ($ temp_key_string, 0,-1); $ temp_value_string = substr ($ temp_value_string, 0,-1 ); // assemble the Insert SQL statement $ this-> SQL = "INSERT "'. $ table_name. "'(". $ temp_key_string. ") VALUES (". $ temp_value_string. ");"; // run the Insert SQL statement $ this-> mysql-> run_ SQL ($ this-> SQL);} // test the output function select _ Output ($ array_data, $ row_name) {foreach ($ array_data as $ key = >$ value) {echo $ value [$ row_name] ;}}?>

Below are a few simple call examples:

// Connect to the database and return the query result $ sqlData = $ this-> SQL _model-> select_limit ('entries ); // pass the database results to $ data ['query'] = $ sqlData; // use the variable $ data to input data to the target webpage $ this-> load-> view ('blog _ view', $ data );

Example of calling the Insert function:

// Store the data to be inserted into the associated array $ data_array ['entry _ id'] = $ _ POST ['entry _ id']; $ data_array ['body'] =_ _ POST ['body']; $ data_array ['author'] =$ _ POST ['author']; // execute the SQL statement $ sqlData = $ this-> SQL _model-> insert_into ('comments', $ data_array );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.