用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2932|回复: 2
收起左侧

[库 Library] 封装了一个单个表格操作类

[复制链接]
发表于 2018-6-6 17:21:33 | 显示全部楼层 |阅读模式
类库源码:
PHP复制代码
/**
 * Class Lw_db 通用类,使用于常用的增删改查操作
 */

class Lw_db
{
    protected $CI;
    private $TB_NAME;
 
    public function __construct($params)
    {
        $this->CI =& get_instance();
        $this->CI->load->database();
        $this->TB_NAME = $params['tb_name'];
    }
 
    /** 获取多条数据
     * @param null $field :字段 默认 "*"
     * @param null $keys : where 关键字
     * @param null $order :排序
     * @param  $orderType :排序类型
     * @param null $limit :返回数据起点,或返回条数
     * @param null $offet :返回条数
     * @return mixed 多维数组数据
     */

    public function get_all($field = null, $keys = null, $order = null, $orderType = 'asc', $limit = null, $offet = null)
    {
        ($field) ? $this->CI->db->select($field) : $this->CI->db->select("*");
        $this->CI->db->from($this->TB_NAME);
        ($keys) ? $this->CI->db->where($keys) : "";
        ($order) ? $this->CI->db->order_by($order, $orderType) : "";
        $this->CI->db->limit($limit, $offet);
        return $this->CI->db->get()->result_array();
    }
 
    /** 获取单条数据
     * @param $keys : where 关键字
     * @return mixed:以为数组数据:字段为键 值为值
     */

    public function get_one($keys)
    {
        return $this->CI->db->get_where($this->TB_NAME, $keys)->row_array();
    }
 
    /** 插入单条数据
     * @param $info :插入数据(数组)键-> 字段名,值-> 插入值
     * @return mixed:返回插入id
     */

    public function insert($info)
    {
        $this->CI->db->insert($this->TB_NAME, $info);
        return $this->CI->db->insert_id();
    }
 
    /** 更新数据
     * @param $info :更新数据(数组)键-> 字段名,值-> 插入值
     * @param $keys :where 关键字
     * @return mixed:返回更新成功与否
     */

    public function update($info, $keys)
    {
        return $this->CI->db->update($this->TB_NAME, $info, $keys);
    }
 
    /** 删除数据
     * @param $keys : where 关键字
     * @return mixed:返回删除成功与否
     */

    public function delete($keys)
    {
        return $this->CI->db->delete($this->TB_NAME, $keys);
    }
}
 
复制代码


简单的调用示例
PHP复制代码
 
// 引入表 tb_user
$this->CI->load->library('lw_db',array('tb_name'=>'tb_user'),'tb_user');
// 获取某个用户
$rowUser = $this->tb_user->get_one(array('id' => 1));
// 获取状态为 1 的所有用户
$rowsUser = $this->tb_user->get_all('*', array('state_id' => 1));
// 插入一条用户
$field = array('name' => 'zZ爱吃菜', 'state_id' => 1);
$rs = $this->tb_user->insert($field);
// 更新一条用户
$field = array('name' => 'zZ爱吃菜2');
$where = array('id' => 1);
$rs = $this->tb_user->update($field, $where);
// 删除一条用户
$rs = $this->tb_user->delete($where);
 
复制代码

评分

参与人数 1威望 +5 收起 理由
Hex + 5 很给力!

查看全部评分

发表于 2018-11-24 22:12:10 | 显示全部楼层
很好。挺实用的!

本版积分规则