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>  

转载于:https://www.cnblogs.com/hanqishihu/p/6039701.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值