Home Backend Development PHP Tutorial Simple ways to use CI framework

Simple ways to use CI framework

Jul 28, 2016 am 08:28 AM
config gt nbsp php this

  1. CodeIgniterFramework
  2. 1, MemoriesMVC
  3. 1.1 , M: model, provide data, save data
  4. 1.2, V: View, only responsible for displaying the form form
  5. 1.3, C: Controller, coordinating the model and view
  6. 1.4 , action: Action is a method in the controller, used to be requested by the browser
  7. 2, CI in MVC
  8. CI Introduction: CodeIgniter is a lightweight but powerful php framework, based on the MVC design pattern.Provides a rich set of class libraries
  9. 2.1, accessed url used pathinfo
  10. 2.2, format: entry file/controller/action ( Default pathinfo format)
  11. 2.3, application Directory:
  12. ControllersControllers
  13. ModelsModels
  14. Views View
  15. 2.4, the default controller is welcome
  16. 2.5, the default action is index
  17. 2.6, file names must be all lowercase
  18. 3, controller (controller):
  19. 3.1, no need to add suffix, just the class name .php
  20. 3.2、 File names are all lowercase, such as user.php (uppercase file names are not supported by browsers)
  21. 3.3, all controllers, directly or indirectly inherited from CI_Controller Classes, the first letter of the class name is capitalized
  22. 3.4, method names are not case-sensitive
  23. Action requirements:1.must start with public
  24. 2. cannot start with an underscore (_)
  25. Attention!If the method name is the same as the class name, it will be regarded as a constructor method (__construct)
  26. 4
  27. , view (
  28. view)
  29. 4.1
  30. , load the view in the controller:
  31. $this->load->view("user_add"); //No Add extension 4.2
  32. , load the view in the controller:
  33. $this->load->view("user/ add”);//Without extension Note: You can call
  34. $this
  35. ->load->view(view); 4.3
  36. , in the view, directly use the native
  37. php code4.4
  38. , assign variables in the controller:
  39. $this->load - >vars("variable name in view", variable name in php); abcdefg ";
  40. $this->
  41. load->vars("str",$str
  42. ); Use in view :php echo $str;?> 4.5, assign multiple variables in the controller:
  43. For example: $str
  44. ="
  45. abcd";
  46. $list =
  47. array("id"=>" 1"," name
  48. ”=>”zhangsan”,”pwd”=>”1234”);$data [“str "]= $str;$data
  49. ["list"]= $list; $this
  50. -> ;load->vars($data); The framework will solve it by itself
  51. php
  52. Short tags ?>4.7, recommended use: phpforeach
  53. (
  54. $list
  55. as
  56. $key => Attributes5.1$this
  57. ->
  58. loadAttributes5.1. 1, instance of loader class system /core/Loader.
  59. php
  60. 5.1.
  61. 2
  62. CI_
  63. Lo Method provided by ader: $this ->load
  64. ->
  65. view()load view$this->load-> vars() Assign variables to the view
  66. $this->load-> ;database()Load database operation object
  67. $this -> load-> )Help objects $this
  68. ->
  69. 5.2, $this->uriattributes
  70. 5.2.1, instance of loader class system/core/URI.php
  71. 5.2.2 Methods provided by , CI_URI:
  72. $this->uri->Segment(n) is used to get URL The n parameter in represents the controller
  73. 1
  74. , the action represents 2, and the value 1 represents 3 , value 2 is represented by 4Usage
  75. 1
  76. : Entry file/controller/action/value1/value2echo $this
  77. - >
  78. uri->segment(3);//Output value 1Usage
  79. 2
  80. : index.php /Controller/Action/6//can be obtained directly; the parameters must correspond correctly
  81. public
  82. function
  83. ($id=0) {echo $id
  84. ;
  85. //output 6}
  86. 5.3$this->inputattribute
  87. 5.3. 1, instance of loader class system Methods provided by /core/Input.php
  88. 5.3.2, CI_Input:
  89. $this ->input->post('username'); //$_POST["username"]; -> ;
  90. input->server("DOCUMENT_ROOT");//$_SERVER["DOCUMENT_ROOT"]$this-&g t;
  91. input -> server ("SERVER_ADDR");//Server-side IPNote: In the view, you can directly use $this
  92. to access the properties in the super object 6, access database 6.1
  93. , modify configuration file: application/config
  94. /database
  95. .php
  96. 6.2 , Load database operation class:
  97. $this->load->database();After successful loading, it will be placed in the properties of the super object, by default The attribute name is db
  98. $this->db6.3, $query= $this
  99. -& gt;db- >
  100. query($sql);
  101. //The return value is the object (array_fetch_object)$sql = $this-> db ->last_query($sql);//Display the last executed sql statement
  102. 6.3.1,$ query= $this-> $list= $query->
  103. $list
  104. = $query-> = $query->row();//Return the first piece of data, which is directly an object6.7,$row=
  105. $query ->row_array();//Return the first data, which is an array6.8, $count=
  106. $query-> num_rows();//Return the number of rows in the result set6.9, $field=
  107. $query->num_fields (); //Return the requested number of fields6.10, $count=
  108. $query->affected_rows();//Return the number of affected rows 6.11$id=
  109. $query->insert_id();//Return self-increasing ID 7 , configuration in the database
  110. 7.1, automatic loading db: in application/config
  111. /autoload .php中Configuration:
  112. $autoload["libraries"]= array("database");
  113. This way you don't need $this -> load->database();
  114. 7.2, parameter binding
  115. $name = $this ->input -> ->post ("pwd");
  116. //Use question marks to bind parameters $data[0]= $name ;
  117. $data[
  118. 1]= $pwd;//Use a two-dimensional array to pass values ​​$sql
  119. =" insertinto ci_user(name,pwd
  120. ) values ​​(?,?)”;//Multiple question marks, you need to pass an index array$bo ol = $this-> The value is boolean 7.3, table prefix configuration is configured in application
  121. /config/database.php: $db[' default']['dbprefix']
  122. ='ci_
  123. ';$db['default '][' swap_pre']='
  124. ci_';'; The configuration is the same. In the code, just write the name after the table prefix directly. If the project table prefix changes in the future, you only need to modify it. $db['default']['dbprefix']=
  125. 'new_', in the code ci_ will be automatically replaced by new_ 8, database operation (
  126. AR model) 8.1, configuration application/ cinfog/database. php$active_record
  127. = TRUE
  128. ;8.2, in the configuration file, after configuring the table prefix,
  129. will be added automatically
  130. 8.3、 Find (get): $res = $this->db->
  131. get('table name'); / /Return the result set object $list
  132. = $res->
  133. result();//Return the array, the array is one object $ list
  134. = $res-> ) ://Data uses associative array$data["database field name"]=
  135. value;//$this->input->post("name ");$data["database field name"]=value;
  136. $res = $this->db -> ;insert("data table name",
  137. $data);//return result boolean;8.5
  138. , modify (update
  139. ): //Data uses associative array$data["database field name"]
  140. =value;//$this->input->post("name"); $data
  141. ["database field name"]=value; $where = array("id" =>" 4 ”);
  142. $res = $this->db->update("data table name",$data,$where ) ;//return result boolean;
  143. 8.6、delete(delete):
  144. $where = array("id ”=> ;"4");
  145. $res = $this->db->dalete("data table name", $where);//Return result boolean;
  146. 9, AR coherent operation
  147. 9.1$res = $this-> -> from("user")//Data table name->
  148. where("id >",3)//Conditions There must be a space between id and >
  149. ->order_by("id desc")//Sort ->
  150. limit(3,1)//Paging; means skip 1 item, take 3 items , opposite to tp
  151. ->get();//Get data$list = $res
  152. ->result _array() ;9.2
  153. , where() conditionsConditional symbols: ">", ">=", "<", "<=", "=", "!="; If you don't specify a condition, the default value is "=" $this->db
  154. ->where("field","value")->get();
  155. For example:
  156. $res = $this
  157. ->db->where("name","admin")-> get ();//"="9.2.
  158. 2$res= $this->db - >where("field=","value")->get();For example: $res=
  159. $this- >db-> When there are spaces 2 or multiple conditions: use array()9.2.3, $res=
  160. $this -> get();For example: $res= $this->db->where( array( "name
  161. " =>"admin","id
  162. >3" =>"2"))-&g t; get();9.2.4, complex query statements use $this->db-> query(
  163. $sql,$data);//Use question marks to bind parameters9.3joinConnection query
  164. 9.3.1, the default is left query (left join on)
  165. $this->db->select("field")
  166. - >from ("data table name")
  167. ->join('join table','join condition')
  168. -> get ();​​ //The default is left query (left join … on) For example:
  169. $this->db->select(“*”)
  170. -> from ("user")
  171. ->join('category', user.id= category. id)//The default is left query (left join )
  172. ->get();
  1. 9.3.2. Select the connection through the third optional parameter of join(). The optional parameters include: left, right, outer, inner, left outer, right outer
  2. For example:
  3. $this->db->select(“*”)
  4. ->from(“user”)
  5. ->join ("category", "user.id = category.id", "left")//Specify through the third parameter
  6. ->get();
  7. 10. Extended CI controller
  8. 10.1. Extending the controller
  9. 1. Create a new controller (MY_Controller) in application/core. The new controller inherits the CI_Controller class and can be extended from the controller you created.
  10. For example: class MY_Controller extends CI_Controller{
  11. Public function __consreuct(){
  12. Parent::__construct(); //Call the constructor of the parent class
  13. //Login verification
  14. //Permission verification
  15. }
  16. }
  17. 2. Let welcome.php inherit the controller you created (MY_Controller) and indirectly inherit CI_Controller.
  18. 3. The controller prefix can be modified
  19. in application/config/config.php:
  20. $config['subclass_prefix'] = 'MY_';
  21. 11. Model
  22. 11.1. Model file naming: user_model.php, category_model.php, file name in lowercase
  23. Recommendation: use _model as the suffix for the model file name to prevent conflicts with Controller class name conflict!
  24. 11.2. All models inherit directly or indirectly from the CI_Model class. The first letter of the class name is capitalized
  25. 11.3. The methods required for creation: getAll()...
  26. 11.4. Loading in the controller Model: $this->load->model("model file name"); //No suffix
  27. 11.5. Alias ​​when loading the model in the controller: $this->load->model ("Model file name", "Alias");
  28. After successful loading, it will be placed in the properties of the super object. The default property name is the model file name or alias
  29. 11.6. Call the model in the controller. Get data: $this->Model file name->Method name();
  30. For example: $this->load->model("User_model"); //Pay attention to the case
  31. $this->User_model->getAll(); //Call the model and get the data
  32. 11.6.1. Call the model in the controller and get the data: $this->alias->Method name() ;
  33. For example: $this->load->model("User_model","user"); //Pay attention to the case
  34. $this->user->getAll(); / / Call the model and get the data
  35. 12. URL related functions in CI
  36. 12.1. Loading helper function: $this->load->helper("url");
  37. Configure automatic loading Helper function: Configure
  38. $autoload['helper'] = array('url');
  39. in application/config/autoload.php, so there is no need to write $this- >load->helper("url");
  40. Helper function:
  41. site_url("Controller/Action/Parameters"); //Process url and parameters
  42. Use in the view
  43. base_url(); //Return to the root directory of the website ("ci/");
  44. 13. in CI Routing and pseudo-static, hidden index.php entry file
  45. 13.1, routing settings
  46. Set/modify in application/config/routes.php:
  47. $route ['default_controller'] = "welcome"; //The default controller is welcome
  48. 13.2, pseudo-static setting
  49. is set in application/config/routes.php/ Modification:
  50. //regular matching (controller/)
  51. $route['news/[d]{6}/([dw ]+).html'] = 'user/show/$1';
  52. http://localhost/CI/index.php/news/201401/caolizhi66.html
  53. will action The parameters in news are routed to user/show/$1
  54. 13.3. Hide the entry file index.php
  55. 13.3.1. Open the apache configuration file: LoadModule rewrite_module modules/mod_rewrite.so
  56. 13.3.2. In the entry file statistics directory, create a .htaccess file with the following content:
  57. RewriteEngine on //Enable pseudo-static
  58. RewriteCond %{ REQUEST_FILENAME} !-d //Match non-existing directories
  59. RewriteCond %{REQUEST_FILENAME} !-f //Match non-existent files
  60. RewriteRule ^(.*)$ index.php/$1 [QSA, PT,L] //Rewrite the rules
  61. This way you don’t have to write the entry file index.php
  62. 14. Pagination in CI
  63. $this->load->library('pagination');
  64. 1 $config['base_url'] = $url;
  65. 2 / * Basic URL for paging
  66. 3 If you want to use the link form of a and b, the url should be in the form of /news/page/
  67. 4 If the link is in the form of c and d, the url should be in the form of /news?
  68. 5 */
  69. 6 $config['total_rows'] = $total;//The total number of records, there is nothing to say about this, it is the total number of records you get from the database
  70. 7 $config['per_page'] = $pagesize; //Number of items per page.Well, there’s not much to say about this. . Set it yourself. The default is 10.
  71. 8 $config['page_query_string'] = TRUE;
  72. 9 /*Parameter form. Turning on true will automatically add &per_page=3 after your url. (This per_page is the default query character. Of course, you can also use $config['query_string_segment'] to set it yourself)
  73. 10 Therefore, the forms in c and d are generally localhost/news?&per_page =2 But it’s all the same, it doesn’t matter. The per_page of get is still 3
  74. 11 */
  75. 12 $config['first_link'] = 'Homepage'; // The first page displays
  76. 13 $config['last_link'] = 'last page'; // The last page displays
  77. 14 $config['next_link'] = 'next page>'; // The next page displays
  78. 15 ​​$config['prev_link'] = '<Previous page'; // Previous page shows
  79. 16 $config['cur_tag_open'] = '<aclass="current">'; // Current page start style
  80. 17 $config['cur_tag_close'] = '</a> ';
  81. 18 /* Ending style of the current page. You can try these yourself.
  82. 19For example, I want the pagination number style of the current page to look better, with red fonts, etc. You can add csscode to current num_links
  83. ' ] = 2;//The number of page numbers displayed before and after the current connection. This means that your current page is page 5
  84. , then you can see pages
  85. 3, 4, 5, 6, 7 . 22 $config['uri_segment
  86. '
  87. ]=4 ;23/*this It is used to determine the number of pages when you use link styles a) and b). 24 For example, the uri_segment of localhost/news/page/3 should be set to 3. localhost/news/title/page/3 This should be set to 425 */
  88. 26
  89. $config
  90. ['
  91. use_page_numbers
  92. '
  93. ]= TRUE;27/*This is the difference between a) and b). When turned on, page will indicate the number of pages. false will indicate the number of records The above introduces the simple use of CI framework, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles