TP框架常用(一)


  1. 25、顯示最后一條查詢的sql語句:主要用於在連貫操作時,檢測拼接的sql語句是否正確   
  2.       
  3.     echo $this->db->last_query();//如:select * from pt_users where uid>10 order by datetime desc limit 0,10   

 

[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 26、CI_DB_pdo_driver PDO數據庫驅動類  
  2.   
  3.     $this->db->affected_rows();//影響記錄數(事務中常用),區分:$this->db->get("order_master")->num_rows();//獲取到的結果集行數  
  4.   
  5.     $this->db->count_all("order_master");//對於某個表不帶條件的查詢  
  6.   
  7.     $this->db->count_all_results();//快捷操作類方法,適用於帶條件的查詢  
  8.   
  9.     $this->db->insert_id();//新插入記錄的id(常用於插入是否成功的判斷)  
  10.   
  11.     $this->db->trans_enabled = true;//開啟事務(默認是false,所以在使用事務前必須將其賦值為true)  
  12.   
  13.     $this->db->trans_begin();//開始事務  
  14.   
  15.     $this->db->trans_rollback();//事務回滾  
  16.   
  17.     $this->db->trans_commit();//提交事務  
  18.   
  19.     $this->db->trans_status();//事務狀態 true 或 false         CI_DB_driver驅動類中的方法  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 27、CI_DB_mysql_driver  mysql數據庫驅動類  
  2.   
  3.     $this->db->affected_rows();//影響記錄數(事務中常用),區分:$this->db->get("order_master")->num_rows();//獲取到的結果集行數  
  4.   
  5.     $this->db->count_all("order_master");//對於某個表不帶條件的查詢  
  6.   
  7.     $this->db->count_all_results();//快捷操作類方法,適用於帶條件的查詢  
  8.   
  9.     $this->db->insert_id();//新插入記錄的id(常用於插入是否成功的判斷)  
  10.   
  11.     $this->db->trans_enabled = true;//開啟事務(默認是false,所以在使用事務前必須將其賦值為true)  
  12.   
  13.     $this->db->trans_begin();//開始事務  
  14.   
  15.     $this->db->trans_rollback();//事務回滾  
  16.   
  17.     $this->db->trans_commit();//提交事務  
  18.   
  19.     $this->db->trans_status();//事務狀態 true 或 false         CI_DB_driver驅動類中的方法  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 28、CI_DB_mysqli_driver  mysqli數據庫驅動類  
  2.   
  3.     $this->db->affected_rows();//影響記錄數(事務中常用)<span id="transmark"></span>,區分:$this->db->get("order_master")->num_rows();//獲取到的結果集行數  
  4.   
  5.     $this->db->count_all("order_master");//對於某個表不帶條件的查詢  
  6.   
  7.     $this->db->count_all_results();//快捷操作類方法,適用於帶條件的查詢  
  8.   
  9.     $this->db->insert_id();//新插入記錄的id(常用於插入是否成功的判斷)<span id="transmark"></span>  
  10.   
  11.     $this->db->trans_enabled = true;//開啟事務(默認是false,所以在使用事務前必須將其賦值為true)  
  12.   
  13.     $this->db->trans_begin();//開始事務  
  14.   
  15.     $this->db->trans_rollback();//事務回滾  
  16.   
  17.     $this->db->trans_commit();//提交事務  
  18.   
  19.     $this->db->trans_status();//事務狀態 true 或 false         CI_DB_driver驅動類中的方法  

 

[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 29、model模型類中引用其它model模型類(如:category_model)和數據庫(如:product)  
  2.   
  3.     public function __construct() {  
  4.         parent::__construct();  
  5.         $this->product_db = $this->load->database('product', true);//通過model基類中的__get()方法選擇性的引入CI超級對象中已加載類庫,如:"load"  
  6.         $this->load->model('category_model');  
  7.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 30、控制器中引用其它模型類(如:category_model)和數據庫(如:product)  
  2.   
  3.     public function __construct() {  
  4.         parent::__construct();  
  5.         $this->product_db = $this->load->database('product', true);  
  6.         $this->load->model('category_model');  
  7.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 31、helper函數中引用CI超級對象的方法  
  2.   
  3.     function get_order_status_by_order($order_status){  
  4.   
  5.         $CI =& get_instance();//獲取CI超級對象  
  6.   
  7.         $CI->load->Model('order_model');//通過CI超級對象可以載入任何模型  
  8.   
  9.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 32、緩存驅動的加載方式  
  2.   
  3.     $this->load->driver('cache', array('adapter' => 'memcached'));//加載緩存驅動或緩存適配器,當前為memcached緩存;注意:CI框架只支持memcached,不支持memcache,windows操作系統下只有memcache擴展  
  4.   
  5.     $this->load->driver('cache', array('adapter' => 'file'));//加載緩存驅動或緩存適配器,當前為file緩存  
  6.   
  7.     $this->load->driver('cache', array('adapter' => 'redis'));//加載緩存驅動或緩存適配器,當前為redis緩存  
  8.   
  9.     $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));//優先選擇apc緩存,file文件緩存作為替代方案;如果服務器不支持apc緩存時,選擇file文件緩存  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 33、靜態html模板文件中如何動態加載區域塊內容  
  2.   
  3.     //index.html文件  
  4.     <div include="/index.php/pub/common_nav" rel="include"></div>  
  5.   
  6.     //jquery代碼  
  7.     $(document).ready(function () {  
  8.         $('[rel=\'include\']').each(function (e) {  
  9.         var t = $(this),  
  10.         url = t.attr('include') + location.search;  
  11.         url && $.get(url, function (data) {//url:'/index.php/pub/common_nav'  
  12.             t.html(data);  
  13.         })  
  14.         })  
  15.     })  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 34、拼接insert sql語句  
  2.     /** 
  3.      *一維關聯數組,拼接sql語句 
  4.      *$data['username']="admin"; 
  5.      *$data['password']="12345"; 
  6.      *$data['sex']=""; 
  7.      */  
  8.     function add_user( $data ) {  
  9.             if ( empty($data) || !is_array($data) ) {  
  10.                 return false;  
  11.             }  
  12.             foreach ($data as $key => $value) {  
  13.                 if ( $value === '') {  
  14.                     unset($data[$key]);//刪除數組中值為空的元素  
  15.                 }  
  16.             }  
  17.             $cols = array_keys($data);//獲取數組所有的鍵名  
  18.             $values = array_values($data);//獲取數組所有的值  
  19.             $cols_str = implode(",", $cols);//將數組所有的鍵名拼接成一個字符串  
  20.             $values_str = "'".implode("','", $values)."'";//將數組所有的鍵值放到單引號中  
  21.             //拼接sql:INSERT INTO user (username,password) VALUES ('admin','12345');  
  22.             $sql = "INSERT INTO user ({$cols_str}) VALUES ({$values_str})";//拼接sql  
  23.             $this->db->query($sql);  
  24.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 35、拼接insert sql語句  
  2.     /** 
  3.      *一維關聯數組,拼接sql語句 
  4.      *$data['username']="admin"; 
  5.      *$data['password']="12345"; 
  6.      *$data['sex']=""; 
  7.      */  
  8.     function add_user( $data ) {  
  9.             if ( empty($data) || !is_array($data) ) {  
  10.                 return false;  
  11.             }  
  12.             foreach ($data as $key => $value) {  
  13.                 if ( $value === '') {  
  14.                     unset($data[$key]);//刪除數組中值為空的元素  
  15.                 }  
  16.             }  
  17.             $cols = array_keys($data);//獲取數組所有的鍵名  
  18.             $values = array_values($data);//獲取數組所有的值  
  19.             foreach($values as $k=>$val){  
  20.                 $values[$k]="'".$val."'";//將所有的鍵值放到單引號中  
  21.             }  
  22.             $cols_str = implode(",", $cols);//將數組所有的鍵名拼接成一個字符串  
  23.             $values_str = implode(",", $values);//將數組所有的鍵值拼接成一個字符串  
  24.             //拼接sql:INSERT INTO user (username,password) VALUES ('admin','12345');  
  25.             $sql = "INSERT INTO user ({$cols_str}) VALUES ({$values_str})";//拼接sql  
  26.             $this->db->query($sql);  
  27.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 36、拼接update sql語句  
  2.     /** 
  3.      * 編輯用戶信息 
  4.      * $userid=1; 
  5.      * $data['username']='admin'; 
  6.      * $data['password']='123'; 
  7.      */  
  8.     function edit_user(userid, $data) {  
  9.         if ( empty($data) || !is_array($data) ) {  
  10.             return;  
  11.         }  
  12.         foreach ($data as $key => $value) {  
  13.             $str .= isset($str)?", {$key} = '{$value}'":"{$key} = '{$value}'";  
  14.         }  
  15.         //拼接sql:UPDATE user SET username='admin',password='123' WHERE addr_id = '1';  
  16.         $sql = "UPDATE user SET {$str} WHERE addr_id = '{$addr_id}'";  
  17.         $this->db->query($sql);  
  18.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 37、數據庫快捷操作類常用方法  
  2.     /** 
  3.      * 查詢訂單 
  4.      * 
  5.      * @param $query 
  6.     */  
  7.     public function get_order_list($query, $offset = 0, $limit = 20) {  
  8.         if (is_array($query) && !empty($query)) {  
  9.             foreach ($query as $key => $val) {  
  10.                 if (is_array($val)) {  
  11.                     $this->order_db->where_in($key, $val);  
  12.                 } else {  
  13.                     $this->order_db->where($key, $val);  
  14.                 }  
  15.             }  
  16.         }  
  17.         $this->order_db->order_by('updatetime', 'desc');  
  18.         $this->order_db->order_by('id', 'desc');  
  19.         if (!$limit) {  
  20.             $query = $this->order_db->get('order');  
  21.         } else {  
  22.             $query = $this->order_db->get('order', $limit, $offset);  
  23.         }  
  24.           
  25.         if ($query->num_rows() > 0) {  
  26.   
  27.             return $query->result_array();  
  28.         }  
  29.   
  30.         return array();  
  31.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 38、拼接select sql語句  
  2.     function get_user_list($cols=array("username","password")) {  
  3.         $col=implode(",",$cols);//查詢的列屬性  
  4.         $sql = "SELECT $col FROM user ORDER BY addr_id DESC";  
  5.         $this->db->query($sql)->result_array();  
  6.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 39、CI框架中cookie的三種使用方式  
  2.   
  3.     //第一種設置cookie的方式:采用php原生態的方法設置的cookie的值  
  4.     setcookie("user_id",$user_info['user_id'],86500);  
  5.     setcookie("username",$user_info['username'],86500);  
  6.     setcookie("password",$user_info['password'],86500);  
  7.     //echo $_COOKIE['username'];  
  8.   
  9.     //第二種設置cookie的方式:通過CI框架的input類庫設置cookie的值  
  10.     $this->input->set_cookie("username",$user_info['username'],60);  
  11.     $this->input->set_cookie("password",$user_info['password'],60);  
  12.     $this->input->set_cookie("user_id",$user_info['user_id'],60);  
  13.     //echo $this->input->cookie("password");//適用於控制器  
  14.     //echo $this->input->cookie("username");//適用於控制器  
  15.     //echo $_COOKIE['username'];//在模型類中可以通過這種方式獲取cookie值  
  16.     //echo $_COOKIE['password'];//在模型類中可以通過這種方式獲取cookie值  
  17.   
  18.     //第三種設置cookie的方式:通過CI框架的cookie_helper.php輔助函數庫設置cookie的值  
  19.     set_cookie("username",$user_info['username'],60);  
  20.     set_cookie("password",$user_info['password'],60);  
  21.     set_cookie("user_id",$user_info['user_id'],60);  
  22.     //echo get_cookie("username");  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 40、array_merge()合並數組函數的使用  
  2.     <?php  
  3.     header("content-type:text/html;charset='utf-8'");  
  4.     $arr1=array(  
  5.           
  6.         "13012"=>array(  
  7.             "brand_id"=>2,  
  8.             "category_id"=>3  
  9.         )  
  10.   
  11.     );  
  12.   
  13.     $arr2=array(  
  14.           
  15.         "13012"=>array(  
  16.             "goods_id"=>3576,  
  17.             "goods_name"=>"sanyang"  
  18.         )  
  19.   
  20.     );  
  21.     /** 
  22.      *echo "<pre>";print_r(array_merge($arr1,$arr2)); 
  23.      *結果: 
  24.      *Array 
  25.      *  ( 
  26.      *      [0] => Array //索引重置為數字索引 
  27.      *          ( 
  28.      *              [brand_id] => 2 
  29.      *              [category_id] => 3 
  30.      *          ) 
  31.      *      [1] => Array 
  32.      *          ( 
  33.      *              [goods_id] => 3576 
  34.      *              [goods_name] => sanyang 
  35.      *          ) 
  36.      *  ) 
  37.      */  
  38.   
  39.      /** 
  40.      *echo "<pre>";print_r(array_merge($arr1['13012'],$arr2['13012'])); 
  41.      *結果: 
  42.      *  Array 
  43.      *  ( 
  44.      *      [brand_id] => 2 
  45.      *      [category_id] => 3 
  46.      *      [goods_id] => 3576 
  47.      *      [goods_name] => sanyang 
  48.      *  )    
  49.      */  
  50.   
  51.     ?>  

 

[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 41.json格式數據:  
  2.        public function json(){  
  3.            $data[0]['goods_id']=3567;  
  4.            $data[0]['goods_name']="sanyang";  
  5.            $data[1]['goods_id']=3567;  
  6.            $data[1]['goods_name']="sanyang";  
  7.            echo json_encode($data);exit;  
  8.            /** 
  9.             * 結果: 
  10.             * [ 
  11.             *    { 
  12.             *        "goods_id": 3567, 
  13.             *        "goods_name": "sanyang" 
  14.             *    }, 
  15.             *    { 
  16.             *        "goods_id": 3567, 
  17.             *        "goods_name": "sanyang" 
  18.             *    } 
  19.             *] 
  20.             */  
  21.        }  

 

[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 42.聯合查詢 left join  
  2. //controller控制器  
  3. $query = array(  
  4.         'product_id' => $product_id,  
  5.         'activity.status' => array(1, 2, 0),  
  6.         'activity.is_del' => 0  
  7. );  
  8. $query['activity.activity_id<>'] = $activity_id;  
  9.   
  10. $goods_list = $this->activity_model->get_activity_good_mapping($query, 0, 0);  
  11.   
  12. //model模型  
  13. public function get_activity_good_mapping($query,$offset = 0, $limit = 0,$get=''){  
  14.         $this->db = $this->activity_db;  
  15.         if (is_array($query) && !empty($query)) {  
  16.             foreach ($query as $key => $val) {  
  17.                 if (is_array($val)) {  
  18.                     $this->db->where_in($key, $val);  
  19.                 } else {  
  20.                     $this->db->where($key, $val);  
  21.                 }  
  22.             }  
  23.         }  
  24.           
  25.         $this->db->from('activity_goods');  
  26.         $this->db->join('activity', 'activity_goods.activity_id = activity.activity_id','left');  
  27.           
  28.         if (!$limit) {  
  29.               
  30.         } else {  
  31.             $query = $this->db->limit($limit, $offset);  
  32.         }  
  33.         $query = $this->db->get();  
  34.         if ($query->num_rows() > 0) {  
  35.               
  36.             return $query->result_array();  
  37.         }  
  38.   
  39.         return array();  
  40. }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. 43.ci框架如何記錄sql日志?  
  2.   
  3. (1)配置日志目錄: 在"application/config/config.php" 文件中配置日志目錄  
  4.    $config['log_path']="/opt/www/logs/";  
  5. (2)在 "system/database/DB_driver.php" 文件的query()方法末尾添加如下語句:  
  6.    log_message( 'db','【sql語句:'.$this->last_query().'】');//這樣所有執行過的sql語句都會按日期時間格式記錄到 "/opt/www/logs/" 目錄下  
  7.    return $RES;  

 

[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. //44、根據條件獲取記錄數(效率最高版)  
  2.     public function get_record_count_by_condition($tablename,$condition,$likecondition,$cols){  
  3.         if(!empty($cols)){  
  4.             $this->db->select("count(*) as num");  
  5.         }else{  
  6.             $this->db->select("count(*) as num");  
  7.         }  
  8.         if (is_array($condition) && !empty($condition)) {  
  9.             foreach ($condition as $key => $val) {  
  10.                 if (is_array($val)) {  
  11.                     $this->db->where_in($key, $val);  
  12.                 } else {  
  13.                     $this->db->where($key, $val);  
  14.                 }  
  15.             }  
  16.         }  
  17.           
  18.         if (is_array($likecondition) && !empty($likecondition)) {  
  19.             foreach ($likecondition as $key => $val) {  
  20.                 $this->db->like($key, $val);  
  21.             }  
  22.         }  
  23.           
  24.         $num_info=$this-><span id="transmark"></span>db->get($tablename)->row_array();  
  25.         if($num_info['num'] > 0){  
  26.             return $num_info['num'];  
  27.         }else{  
  28.             return 0;  
  29.         }  
  30.     }  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. //45、去除$aid_arr_temp數組中元素  
  2. foreach($content_list_temp_recommend as $k=>$v){  
  3.     $kk=array_search($v['aid'], $aid_arr_temp);//$v['aid']必定是$aid_arr_temp數組內元素之一的情況  
  4.     $msg.=$aid_arr_temp[$kk].",";  
  5.     if($kk !== false){//只要不是false就是找到了  
  6.         unset($aid_arr_temp[$kk]);//刪除后,索引鍵保持不變  
  7.     }  
  8. }  
  9. $aid_arr=  array_values($aid_arr_temp);//經過array_values()函數處理過后,索引鍵重新分配  
[php] view plain copy
 
 print?在CODE上查看代碼片派生到我的代碼片
    1. //46、處理提交數據為0的情況 下拉菜單:""-全部 0-未審核 1-已審核  
    2. //$state = $this->input->post('state', true) ? $this->input->post('state', true):"";//值始終為空  
    3. $state = is_numeric($this->input->post('state', true)) ? $this->input->post('state', true):"";//0時值為0,空時值為空  
    4. if(is_numeric($state)){  
    5.     $condition['state']=$state;//字段值為0  
    6. }else{  
    7.         $state="";  
    8. }  
    9. $data['state']= (string)$state  
    10. $this->load->view('content_list', $data);  
    11.   
    12.   
    13. <td>  
    14.     <label>狀態:</label>  
    15. </td>  
    16. <td>  
    17.     <select name="state" class="combox">  
    18.     <option value="" <?php if( "" ===$state)echo 'selected'?>>全部</option>  
    19.     <option value="0" <?php if("0" === $state)echo 'selected'?>>未審核</option>  
    20.     <option value="1" <?php if("1" === $state)echo 'selected'?>>已審核</option>  
    21.     </select>  
    22. </td>  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM