2014年10月23日 星期四

CodeIgniter 學習筆記(三)

一、model
1. model is db class
2. on model is one table

二、use ci to create model

1. 目錄/models/
2.
   class Model_name extend CI_Model{
      function _construct(){
        parent::_contruct();
      }
   }
3. ci 為我們提供db class
    Active Record class
    \system\database\DB_active_rec.php
    >> to use :
         $this->db->方法名()
     example:  $this->db->get('entries',10);


三、和db連結

    $this->load->model(model_name);

 1. 連線資料庫
     $this->load->database();

2. insert
    $this->db->insert(table_name, $value);

3. update
   $this -> db -> where(column_name, value);
   $this -> db -> update(table name , update value);

4. select
   $this -> db -> where(column_name, value);
   $this -> db -> select(column_name);
  $query = $this -> db -> get(table name);
   return $query -> result();

5.delete
   $this->db->where(column name ,  value);
   $this->db->delete(table_name);


四、example

1. 建立資料庫ci ,table名稱為user,欄位是uname upass

2. 設定資料庫 application/config/database.php

3. 建立model   test_model.php
Class Test_model extends CI_Model{
 
 function __construct(){
        parent::__construct();
  $this->load->database();
    }

 function user_insert($arr){
  $this->db->insert('user',$arr);   
 }
 
 function user_update($id,$arr){
  $this->db->where('uid', $id);
  $this->db->update('user',$arr);
 }
 
 function user_del($id){
  $this->db->where('uid', $id);
  $this->db->delete('user');
 }
 
 function user_select($name) {
  $this->db->where('uname', $name);
  $this->db->select('*');
  $query=$this->db->get('user');
  return $query ->result();
 }
 
}
4. 建立controller   user.php
class User extends CI_Controller {
 
 function insert(){
  $this->load->model('test_model'); 
  $arr = array ('uname' => "roshiko", 'upass' => "123456");
  $this->test_model-> user_insert($arr);
 }
 
 function update(){
  $this->load->model('test_model'); 
  $arr = array ('uname' => 'roshiko', 'upass' => '1234567');
  $this->test_model-> user_update(3,$arr);
 }
 
 function del(){
  $this->load->model('test_model'); 
  $this->test_model->user_del(1);
 }
 
 function select(){
  $this->load->model('test_model'); 
  $query = $this->test_model->user_select('roshiko');
  foreach ($query as $row){
   echo $row->uid;
   echo $row->uname;
   echo $row->upass;
  }
 }
}

沒有留言:

張貼留言