php 生成crud类,(PHP)CRUD类及分页类

之前写的crud类实在比较简单(http://blog.csdn.net/yycai/archive/2009/12/15/5012353.aspx),重新封装了一下:

/**

* 自动化数据表操作类

* @example

*

* $db = cls_crud::factory(array('table'=>'article'));

* $data = $db->get_block_list(array('category_id' => 3), 9);

*

* $data = $db->get_list(array('title', 'id', 'time'), array('category_id'=>$cid), 'time', 1, $_GET['page'], 2, 1);

* $page_html = $db->page->get_html("?action=list&cid={$cid}", 'ylmf-page');

*

*

* @author 小蔡

* @version 1.2

*/

class cls_crud

{

private static $_instance = null;

/**

* 数据表名

* @var string

*/

private $table = '';

private $link;

private $query_id;

/**

* 分页对象

* @var array

*/

public $page = null;

/**

* 私有构造函数(单例模式)

* @param

*/

private function __construct()

{

}

/**

* 配置

* @param array $config配置变量

*/

private function config($config)

{

if(!empty($config))

{

foreach($config as $cf => $val)

{

$this->$cf = $val;

}

}

}

/**

* 工厂函数

* @param array $config配置变量(最基本要配置数据表名)

* @param array $database数据库链接参数

*/

public static function factory($config, $database=array())

{

if (null === self::$_instance)

{

self::$_instance = new self();

self::$_instance->connect($database);

self::$_instance->page = new cls_page();

}

self::$_instance->config($config);

return self::$_instance;

}

/**

* 设置数据表(例如:在操作的过程中需要改变数据表,就可以使用此方法)

* @param string $table

*/

public function set_table($table)

{

$this->table = $table;

}

/**

* 连接数据库+选择数据库...

* @return void

*/

private function connect($database = array())

{

if(empty($database))

{

include __CONFIG__.'/inc_database.php';

}

try

{

$this->link = @mysql_connect($database['db_host'],$database['db_user'],$database['db_pass']);

if(!$this->link)

{

throw new cls_dbexception(mysql_error());

}

else

{

if($this->server_info() > '4.1')

{

$charset = str_replace('-', '',strtolower($database['db_charset']));

mysql_query("SET character_set_connection=".$charset.", character_set_results=".$charset.", character_set_client=binary",$this->link);

}

if($this->server_info() > '5.0')

{

mysql_query("SET sql_mode=''",$this->link);

}

if(!@mysql_select_db($database['db_name'],$this->link))

{

throw new cls_dbexception(mysql_error());

}

}

}

catch (cls_dbexception $e)

{

die($e->getError());

}

}

/**

* 返回数据库版本...

* @return string

*/

private function server_info()

{

return mysql_get_server_info();

}

/**

* 向数据库查询sql语句...

*

* @deprecated INSERT UPDATE DELETE

* @param string $sql

* @return bool

*/

public function query($sql)

{

try

{

$this->query_id = @mysql_query($sql,$this->link);

if(!$this->query_id)

{

throw new cls_dbexception(mysql_error());

}

else

{

$GLOBALS['QUERY_NUM']++;

return $this->query_id;

}

}

catch (cls_dbexception $e)

{

die($e->getError());

}

}

/**

* 读取一条记录

* @param string $id主键

* @param string $fields获取字段

* @return array

*/

public function read($id, $fields='*')

{

$sql = "SELECT {$fields} FROM `{$this->table}` WHERE `id`='{$id}'";

$this->query($sql);

return $this->fetch_one();

}

/**

* 插入一条记录

* @param array $array数组

* @return bool

*/

public function insert($array)

{

$fields = array();

$values = array();

foreach($array as $f => $v)

{

$fields[] = "`{$f}`";

$values[] = "'".mysql_real_escape_string($v)."'";

}

$fields = implode(',', $fields);

$values = implode(',', $values);

$sql = "INSERT INTO `{$this->table}`({$fields}) VALUES({$values})";

return $this->query($sql);

}

/**

* 更新一条记录

* @param int $id主键

* @param array $array数据数组

*/

public function update($id, $array)

{

$values = array();

foreach($array as $f => $v)

{

$values[] = "`{$f}`='".mysql_real_escape_string($v)."'";

}

$values = implode(',', $values);

$sql = "UPDATE `{$this->table}` SET {$values} WHERE id='{$id}' LIMIT 1";

return $this->query($sql);

}

/**

* 删除一条记录

* @param int $id主键

* @return bool

*/

public function delete($id)

{

$sql = "DELETE FROM `{$this->table}` WHERE id='{$id}' LIMIT 1";

return $this->query($sql);

}

/**

* 获取分页列表的数据

* @example

*

* 参数:$wheres = array('id'=>23, 'NOT(`name` IS NULL)')

* ==> `id`='23' AND NOT(`name` IS NULL)

*

* @param string|array$fields需要读取的字段(注:如果是字符串,则需要对字段名加上“``”标识)

* @param array $whereswhere条件数组,如果下标是数字,则直接加入条件,否则组合成:`{下标}`='{值}'这样的条件。最后用and链接

* @param string $order排序字段

* @param int $desc是否是降序

* @param int $offset偏移量

* @param int $limit读取记录数

* @param int $return_total是否返回满足条件的记录总数,默认为0,需要显示分页时可以设置为1.(如果需要获取分页代码,此值必须为1)

* @return array

*/

public function get_list($fields="*", $wheres=array(), $order='', $desc=1, $page=1, $limit=20, $return_total=0)

{

//处理需要读取的字段

if(is_array($fields) && !empty($fields))

{

$fields = '`'.implode('`,`', $fields) . '`';

}

//处理where条件

if($wheres)

{

$where = array();

foreach($wheres as $f => $v)

{

if(is_numeric($f))

{

$where[] = $v;

}

else

{

$where[] = "`{$f}`='".mysql_real_escape_string($v)."'";

}

}

$where = implode(' AND ', $where);

}

else

{

$where = '1';

}

//处理orderby

$orderby = '';

if(!empty($order))

{

$orderby = "ORDER BY `{$order}` " . (1===$desc ? 'DESC' : 'ASC');

'id'!=$order && $orderby .= ", `id` DESC";

}

$this->page->set_page($page, $limit);

echo $sql = "SELECT {$fields} FROM `{$this->table}` WHERE {$where} {$orderby} LIMIT {$this->page->offset}, {$this->page->limit}";

//var_dump($this);

$this->query($sql);

$data = $this->fetch_all();

//var_dump($sql);

if($return_total)

{

//返回记录总数(分页)

$sql = "SELECT count(*) FROM `{$this->table}` WHERE {$where}";

$this->query($sql);

$total = $this->fetch_one();

$this->page->set_total(current($total));

}

return $data;

}

public function get_block_list($wheres, $limit, $fields="*", $order='id')

{

$data = $this->get_list($fields, $wheres, $order, 1, 0, $limit);

return $data;

}

/**

* 返回单条记录数据...

* @deprecated MYSQL_ASSOC==1 MYSQL_NUM==2 MYSQL_BOTH==3

* @param int $result_type

* @return array

*/

public function fetch_one($result_type = 1)

{

return mysql_fetch_array($this->query_id,$result_type);

}

/**

* 返回多条记录数据..

* @deprecated MYSQL_ASSOC==1 MYSQL_NUM==2 MYSQL_BOTH==3

* @param int $result_type

* @return array

*/

public function fetch_all($result_type = 1)

{

while($row = mysql_fetch_array($this->query_id,$result_type))

{

$row_array[] = $row;

}

return $row_array;

}

}

/**

* 分页类(与crud类结合使用)

* @author 小蔡

* @version 1.1

*/

class cls_page

{

public $offset = 0;

public $limit = 20;

public $total = 0;

private $page = 1;

private $pagenum = 0;

private $style = 'pages';

/**

* 设置当前页码

* @param $page

*/

public function set_page($page = 1, $limit = 20)

{

//当前页数

$this->page = intval($page);

$this->limit = intval($limit);

if(!$this->page || $this->page < 1)

{

$this->page = 1;

}

$this->offset = $this->limit * ($this->page - 1);

}

/**

* 设置总记录数

* @param $total

*/

public function set_total($total)

{

$this->total = intval($total);

if(!$this->total || $this->total < 1)

{

$this->total = 0;

}

$this->pagenum = ceil($this->total / $this->limit);

}

/**

* 获取分页代码

* @param $url

* @return string

*/

public function get_html($url, $style='')

{

$source = '';

if($this->page > $this->pagenum)

{

$this->page = $this->pagenum;

}

if(!empty($style))

{

$this->style = $style;

}

if($this->pagenum > 1)

{

$source = "

首页 ";

$next = $this->page + 1;

$pre = $this->page - 1;

if($this->page > 1)

{

$source .= "上一页";

}

$flag = 0;

for($i = $this->page - 5; $i <= $this->page - 1; $i++)

{

if($i > 0)

{

$source .= " $i ";

}

}

$source .= "".$this->page."";

if($this->page < $this->pagenum)

{

for($i = $this->page + 1; $i <= $this->pagenum; $i++)

{

$source .= " $i ";

$flag++;

if($flag == 5)

{

break;

}

}

}

if($this->page < $this->pagenum)

{

$source .= "下一页";

}

$source .= "pagenum."/">尾页

";

}

return $source;

}

}

?>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值