Z-BlogPHP数据类型详解
本文将介绍自定义数据类型及数据库建表和 CURD 操作步骤,接下来所用代码需要由主程序 1.7 版本及更高版本实现。
一、定义数据结构
新增数据结构是对全局变量$table,$datainfo数组的项目添加:
$table['Custom'] = '%pre%plugin_custom';
# 注意表名可自定义,但必须加上%pre%区分同一数据库中的不同的程序所生成的表
$datainfo['Custom'] = array(
'ID' => array('cu_ID','integer','',0),
'Content' => array('cu_Content','string',250,''),
'LogID' => array('cu_Logid','integer','',0)
# datainfo 数组第一项,必须是'ID',这是表的唯一自增序列
数据表结构 $datainfo 声明结构如下:
array('属性名' => array('字段名', '类型', '长度参数(根据类型定义)', '默认值'));
array('ID', 'integer', '', 0),
array('Check', 'boolean', '', false),
array('Value', 'char', 10, ''),
array('Title', 'string', 250, ''),
array('Content', 'string', '', ''),
二、创建数据类型
自定义数据类型是创建一个继承自系统的Base类的新类:
#这里定义了一个最基本的Custom类,可以在这个类里扩展自己的方法
class Custom extends Base
public function __construct()
parent::__construct($zbp->table['Custom'], $zbp->datainfo['Custom'], __CLASS__);
三、创建数据表
创建数据库的数据表,在应用的include.php页面里的安装函数进行数据库表的存在判断及创建:
function InstallPlugin_应用ID()
if(!$zbp->db->ExistTable($zbp->table['Custom']))
$s = $zbp->db->sql->CreateTable($zbp->table['Custom'], $zbp->datainfo['Custom']);
$zbp->db->QueryMulit($s);
# PS:应用卸载时可根据自身需求来删除数据表或保留所创建的数据表
四、删除数据表
删除数据库中数据表的方法 具体什么时候删,自行决定:
if ($zbp->db->ExistTable($zbp->table['Custom'])) {
$s = $zbp->db->sql->DelTable($zbp->table['Custom']);
$zbp->db->QueryMulit($s);
# PS:应用卸载时可根据自身需求来删除数据表或保留所创建的数据表
五、自定义CURD操作
1、新增一条数据
echo $c->ID; //输出 新插入的对象的ID值
2、更新一条数据
if ($c->LoadInfoByID(1) == true) {
3、删除一条数据
if ($c->LoadInfoByID(2) == true) {
4、查询单条数据
#LoadInfoByID返回值为false即加载不成功
5、查询多条数据
$w[] = array('=', $zbp->d['Custom']['LogID'][0], 123);//查询条件1,LogID值为123
$w[] = array('=', $zbp->d['Custom']['Content'][0], 'abc');//查询条件2,Content值为abc
$sql = $zbp->db->sql->Select($zbp->t['Custom'], array('*'), $w);
$list = $zbp->GetListType('Custom', $sql);
主程序 1.7.2 版新增的查询方法:
主程序 1.7.2 在定义Custom类成功后,自动生成了ZBlogPHP类下的 3 个读取加载Custom类的方法,分别是:
GetCustomList($select = null, $where = null, $order = null, $limit = null, $option = null)
$sql = $zbp->db->sql->get()
->select($zbp->table['Custom'])
->where(array('=', 'cu_Logid', '123'))//查询条件1,LogID为123
->where(array('=', 'cu_Content', 'abc'))//查询条件2,Content值为abc
->orderBy(array('cu_ID' => 'desc'))//排序按ID序号的倒序
$list = $zbp->GetCustomList($sql);
#如果取不到数据$list就返回一个空array()
$c = $zbp->GetCustomByID(111);
#从数据库中查询ID值等于给定数组项目的Custom实例队列
#如果是查询ID值,$field_name参数可以省略
$list = $zbp->GetCustomByArray(array(1,3,5,666));
#返回队列为一个Custom实例的数组(ID分别为1,3,5,666,如果ID存在的话)
介绍GetCustomByArray的一个隐藏的复杂用法:
#设有一个posts文章数组,内有3个post实例对象,ID分别为1,2,13
#查询Custom数据表中LogID值等于posts里post实例ID值的Custom实例队列
$list = $zbp->GetCustomByArray($posts, array('ID' => 'LogID'));
#返回队列为一个Custom实例的数组,它们的LogID都是1或2或13