CodeIgniter, after reading this, you can use it to do the project.

Source: Internet
Author: User
Tags autoload php foreach vars codeigniter

First, MVC
1, entry file
The only script file that allows the browser to request directly
2, controller controllers
Responsible for reconciling models and views
3, model
Only responsible for providing data, saving data
4, view
Display only, and collect user input (form)
5,action Action
is a method in the controller that is used by the browser to request

--------------------------------------------
Second, the MVC in CI
1,pathinfo mode http://localhost/php/ci/index.php/Controller file/action
In the application directory
Controller controllers
Views View
Models model

-------------------------------------------------------------------------
Third, the controller
1, do not need to add a suffix, directly is the class name. php
2, file name all lowercase
3, all controllers need to inherit directly or indirectly from the Ci_controller class
4, the method that starts with an underscore, cannot be requested by the browser, but can be called internally
5, only the public method in the controller can be used as an action
6, method names are case insensitive
7, the same method as the class name, will be used by PHP as a construction method, so do not create the same method as the class name

---------------------------------------------------------------------------------------
Four, view
1, how to load the view in the controller
   

$this->load->view (view);//Direct write view name without extension


2, use native PHP code directly in view, do not use template engine
3, assigning variables in the view

    

$this->load->vars (' title ', ' This is the title ');    $data [' title '] = "This is the title";    $data [' list '] = $list; $this->load->vars ($data); Can be called multiple times  

In the View
      

<?php foreach ($list as $item): ><tr><td><?php echo $item [' id '];? ></td><td><? PHP echo $item [' name ']; ></td><td><?php echo $item [' email '];? ></td></tr><?php Endforeach;?>


4, recommended use

       

<?php foreach ($list as $item):?> <?php Endforeach;?>


-------------------------------------------------------------------------------
V, CI's Super Object
The current Controller object
Properties
$this->load 
instance of the loader class
The method provided by the Loader class:
view () load View
VARs () allocation variable
database () Mount database Operations Object
Model () loaded in Model
Helper () helper

$this->uri
is an instance of the Ci_uri class
Ci_uri provides methods:
Segment () Used to get the value of a segment in the URL  
traditional pathinfo
Portal file. php/Controller/action/parameter 1/value 1/parameter 2/value 2
ci pathinfo
Portal file. php/Controller/action/value 1/value 2
$this->uri->segment (3);//corresponds to a value of 1
$this->uri->segment (4);//corresponds to a value of 2

Public Function index ($p =    0) {
echo $p;

$this->input () input class
is an instance of Ci_input ()
provided method
$this->input->post (' username ');//$_post[' Username '] (no get, can use Segment ())
$this->input->server (' document_root ');

In the view, you can use $this directly with the Super object

---------------------------------------------------------------------------- --------------
VI, database access
Modify the configuration file
application/config/database.php

to mount the database Access object to the properties of the Super object $this->db
$this->load->database ();
$res = $this->db->query ($sql);//Returns an object
$res->result ();//Returns an array that is an object of one of the
$res->result_a Rray (); Returns a two-dimensional array, which is an associative array
$res->row ();//Returns the first record, directly an object
$res->row_array ();//array of the first record


Program Instance
1, Query

Public Function Showusers () {//Load Database operation class $this->load->();//The property of the Super object is placed after the load succeeds, the default property name is Db///var_ Dump ($this->db); $sql = "SELECT * from Blog_user";//Returns an object $res = $this->db->query ($sql);//mysql_query ()// Var_dump ($res); The return value is an object $users = $res andresult ();//mysql_fetch_object (); Returns an object//mysql_fetch_assoc (); Returns an associative array $data[' user_list '] = $users; $this->load->view (' index/users ', $data);}     



2, adding

Public function add{$this->load->database () $sql = "INSERT into Blog_user (Name,password) VALUES (' Mary ', MD5 (' Mary ') "; $bool = $this->db->query ($sql), if ($bool) {//mysql_affected_rowsecho $this->db- >affected_rows (); Number of rows affected echo $this->db->insert_id (); Self-increment ID}}     


In the above two examples, there are security issues, and table prefixes can not automatically modify the problem, the following examples of these two issues have been improved

1, modify (table prefix and parameter binding)

Public Function Test8 () {///Here you can configure "auto-load" in autoload.php, $autoload [' libraries '] = Array (' database ');//$this Load->database ();//$name = $this->input->post (' name '); $data [0] = ' Lili '; $data [1] = ' Lili ';//$DB [' Default ' [' swap_pre '] = ' swap_ '; exchange table prefixes in database configuration files $sql = "INSERT into Swap_user (Name,password) VALUES (?,?)" ; $bool = $this->db->query ($sql, $data);//sql statements have multiple? , you need to pass in an indexed array if ($bool) {echo ' adds success! ";}}




Vii. AR model in the database (Active Record)
1, in the database.php file
$active _record = TRUE;
2, automatic loading
$autoload [' libraries '] = Array (' database ');
3, in the configuration file, when the table prefix is configured, it is automatically added
    

        $res = $this->db->get ("table name");    Returns the result set object $res , and result ();    $this->db->insert (' table name ', associative array);    $bool = $this->db->update (' table name ', associative array, condition); $bool = $this->db->delete (' table name ', condition);      



Consistent operation

Select Id,name from TableName where ID >= 3 ORDER BY id desc limit 2,3$res = $this->db->select (' Id,name ')- >from (' user ')->where (' ID >= ', 2)->limit (3,2)//Skip 2 Strip 3 data->order_by (' id desc ')  Get (); Var_dump ($res,result ()); Echo $this->db->last_query ();     



Some uses of->where ()

$res = $this->db->where (' name = ', ' Zhongshan ')->get (' user ');//$res = $this->db->where (' Name! = ', ' Zhongshan ')->get (' user '), $res = $this->db->where (' name ' = ' Mary ', ' ID > ' + 2) '->get (' user ‘);



For complex queries, please use $this->db->query ($sql, $data); Use? Binding parameters

Viii. How to extend the controller of CI
Write your own controller, application/core/my_controller.php file
Other controllers can inherit from My_controller
In config.php, you can modify the prefix $config [' subclass_prefix '] = ' my_ ';

Class My_controller extends ci_controller{//construction method will automatically call public function __construct () {parent::__construct ();  Call the construction method of the parent class//Login verification ...//permission verification ... }public function funcname () {}   

Nine, the model
Inherit from Ci_model
In the model, you can use the properties of the Super object
File name all lowercase, class name first letter uppercase
It is recommended to use _model as a suffix to prevent and controller class name conflicts
Program code
Model

<? PHP/*** User model * @author Zhongshan <[email protected]>*/class User_model extends ci_model{// return all users    Public Function GetAll () {        $res = $this->db->get (' user ');        return $res result ();}    }        


Controller

<? PHP class User extends my_controller{public Function Index () {//load model, can be an alias, after loading is complete, automatically becomes the property of the Super object $thi    S->load->model (' User_model ', ' User '); $list = $this->user->getall ();  Call the model, get the data $this->load->view ("User/index", Array (' list ' = $list)); }}

Views

<! DOCTYPE html>



X. URL-related functions
$this->load->helper (' url ');//You can configure automatic loading as needed, in autoload.php
Site_url (' controller/method ')
Base_url ()

Xi. setting up a route
application/config/routes.php
Default Controller
$route [' default_controller '] = "welcome";

Http://localhost/php/ci/index.php/news/123456/4.html
$route [' news/[\d]{6}/([\d]+] \.html ') = ' article/show/$1 ';

12. Hide the entry file
Open Apache's rewrite module, in the httpd.conf file
LoadModule Rewrite_module modules/mod_rewrite.so
Restarting the server
Put the. htaccess file in the root directory

13. Paging Class

Load class file $this->load->library (' pagination ');//Display 10 data per page $page_size = ten; $config [' base_url '] = Site_url ( ' User/test ');//How many data $config[' total_rows '] = +;//How many $config[' per_page ' are displayed per page = $page _size; $config [' First_link '] = ' home '; $config [' next_link '] = ' next page '; $config [' uri_segment '] = 3;//The Paging data query offset on which segment $this-> Pagination->initialize ($config); $offset = Intval ($this->uri->segment (3));//and $config [' uri_segment '] corresponding $sql = "SELECT * from user limit {$offset},{$page _size}"; echo $sql;//Create link $data[' links '] = $this Pagination->create_links (); $this->load->view (' user/test ', $data);        

14. File Upload
1, manually create a good upload directory
2, program example
Form

<form action= "<?php echo site_url (' user/upload ');?>" method= "post" enctype= "Multipart/form-data" > < Input type= "file" name= "pic"/><input type= "Submit" value= "Commit"/> </form>


Controller

Public function upload () {//upload directory needs to be created manually $config [' upload_path '] = './uploads/';  $config [' allowed_types '] = ' gif|png|jpg|jpeg ';  Generate a new file name $config [' file_name '] = uniqid();  Load file Upload class $this->load->library (' upload ', $config);  $this->upload->do_upload (' pic ');  Var_dump ($this->upload->data ());  Get the data after uploading $data = $this->upload->();  $filename = $data [' file_name ']; echo $filename;}         

XV, session

Public Function Login () {//Generate a random string as an encryption key//save to config.php in the $config [' encryption_key '] = ';  echo MD5 (UNIQID ()); exit;  $this->load->library (' Session ');  $user = array (' ID ' =>3, ' name ' = ' Jack ');  Session_Start ();  $_session[' user '] = $user;  $this->session->set_userdata (' user ', $user); Do not get the data put in here, only the page reload or jump to another URL in order to get//one-time data, can only read once $this->session->set_flashdata (' index ', ' Abcdefghij ' );}  Public Function show_session () {$this->load->library (' Session ');  Take the data in the CI session $user = $this->session->userdata (' user ');  Var_dump ($user);  Next refresh, there is no $test = $this->session->flashdata (' index '); echo $test;}          


16. Verification Code

Public function Valid () {$this->load->helper (' Captcha '); $vals = array(' word ' = = rand (1000,9999), ' img_path ' = '/captcha/', ' img_url ' = ' base_url (). '  /captcha/', ' img_width ' = +, ' img_height ' = +, ' expiration ' + 60*10//Expiration time, time to, will automatically delete the picture );  $cap = Create_captcha ($vals);  echo $cap [' image '];  echo $cap [' word '];  Session_Start(); When validating, compare $_session[' cap '] $_session[' cap ' = $cap [' word '];}        

17. Form Verification
Controller files

Public Function Insert () {//Var_dump ($this->input->post (' name '));  $this->load->library (' form_validation ');  $this->form_validation->set_rules (' name ', ' username ', ' required ');  $this->form_validation->set_rules (' email ', ' email ', ' valid_email ');  $bool = $this->form_validation->run ();  if ($bool) {//Call model saved to database }else{//Display error message $this->load->view (' User/add '); }}


View File

<?php echo validation_errors ();? ><form action= "<?php echo site_url (' User/insert ');? > "method=" POST ">name:<input type=" text "name=" name "value=" <?php Echo set_value (' name ');? > "><?php echo form_error (' name ', ' <span> ', ' </span> ');?><br>Pass: <input type=" Password "name=" pass "><br> Age: <input type=" number "name=" age "><br>sex: <input type= "Text" name= "sex" ><br>email: <input type= "text" name= "email" value= "<?php Echo set_value (' email '); > "><?php echo form_error (' email ', ' <span> ', ' </span> '); ><br><input type=" Submit " Value= "Submit" >        













CodeIgniter, after reading this, you can use it to do the project.

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.