ThinkPHP相信PHP程序员对它并不陌生,通过自己的学习在此发表个人看法,也为以后自己查找ThinkPHP方面的知识更加方便。
一、mvc及数据库CURD操作流程:
1、新建数据库:数据库名称:17joysdb 数据库用户名:root 数据库密码:空
2、创建数据库表:joys_user,mysql代码如下:
CREATE TABLE `joys_user`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` VARCHAR( 150 ) NOT NULL, `password` VARCHAR( 100 ) NOT NULL, `name` VARCHAR ( 255 ) NOT NULL, `email` VARCHAR ( 100 ) NOT NULL, `reg_date` DATETIME NOT NULL, `last_login_date` DATETIME NOT NULL, `active` TINYINT( 1 ) NOT NULL, `params` TEXT NOT NULL, INDEX ( `name` ), UNIQUE ( `username` ), UNIQUE ( `email` ) ) ENGINE = MYISAM;
3、配置ThinkPHP、数据库的配置:
(1)把ThinkPHP框架拷贝到根目录下;
(2)根目录创建Admin文件夹;
(3)新建admin.php(注意字符集),代码如下;
//定义项目名称 define(‘APP_NAME‘,‘Admin‘); //定义项目路径 define(‘APP_PATH‘,‘Admin‘); //定义ThinkPHP框架路径 define(‘THINK_PATH‘,‘./ThinkPHP‘); //加载ThinkPHP框架核心文件 require THINK_PATH.‘/ThinkPHP.php‘; //实例化项目应用,运行项目 App::run();
(4)运行http://127.0.0.1/admin.php
(5)根目录新建config.inc.php公共配置文件(代码如下):
return array( //‘配置项‘=>‘配置值‘ ‘DB_TYPE‘=>‘mysql‘, ‘DB_HOST‘=>‘localhost‘, ‘DB_NAME‘=>‘17joysdb‘, ‘DB_USER‘=>‘root‘, ‘DB_PWD‘=>‘‘, ‘DB_PREFIX‘=>‘joys_‘, ‘DB_CHARSET‘=>‘utf8‘, );
(6)/Admin/Conf目录下配置config.php(合并公共配置文件和单独配置),代码如下:
$config = require ‘./config.inc.php‘; $array = array( //‘配置项‘=>‘配置值‘ ‘PAGESIZE‘=>10, ‘APP_DEBUG‘=>true, ‘MODULES‘=>array( ‘Menu‘=>‘菜单模块‘, ‘LatestNews‘=>‘最新文章模块‘, ), ); return array_merge($config,$array);
4、创建MVC编程模式流程:
(1)/Admin/Lib/Model目录下新建UserModel.class.php(代码如下):
class UserModel extends Model{ //表单的数据验证 protected $_validate = array( //array(验证的字段,验证的规则,错误提示,验证条件,附加规则,验证时间) /* * 验证规则详解: * 1、验证的字段:数据库字段或者映射字段 * 2、验证规则: * require(验证是否为空)、email、url、currency、number、zip、integer、double、english * 3、错误提示:用于提示错误 * 4、验证条件(可选): * Model::EXISTS_TO_VAILIDATE 或者0 存在字段就验证 (默认) * Model::MUST_TO_VALIDATE 或者1 必须验证 * Model::VALUE_TO_VAILIDATE或者2 值不为空的时候验证 * 5、附加规则: * regex 正则验证,说明前面的那个验证规则是一个正则表达式; * function 使用函数验证,说明前面的那个验证是个函数名; * callback 使用方法验证,说明验证规则是一个Model类的方法; * confirm 验证表单中的两个字段是否相等,验证规则是一个字段名; * equal 验证是否等于某个值,这个值是有前面的验证规则定义的; * in 验证是否在某个范围之内,前面定义的是一个数组; * unique 验证是否唯一,系统会根据字段目前的值查询数据库来判断时候存在相同的值; * 6、验证时间: * Model::MODEL_INSERT(1):插入式验证; * Model::MODEL_UPDATE(2):更新是验证 * Model::MODEL_BOTH(3):所有时间都验证 */ array(‘uname‘,‘require‘,‘用户账号必须填写‘,1,‘regex‘,3), array(‘uname‘,‘‘,‘用户账号已经存在‘,1,‘unique‘,1), array(‘pwd‘,‘require‘,‘密码必须填写!‘), array(‘email‘,‘email‘,‘邮箱格式错误‘), array(‘active‘,array(0,1),‘数据错误‘,0,‘in‘), array(‘password‘,‘checkPwd‘,‘密码长度不够6位‘,1,‘function‘), //array(‘pwd‘,‘checkPwd‘,‘密码长度不够6位‘,1,‘callback‘), ); function checkPwd(){ $password = $_POST[‘pwd‘]; if(strlen($password)>=6){ return true; }else{ return false; } } //表单与字段的映射 protected $_map = array( ‘uname‘=>‘username‘, ‘pwd‘=>‘password‘, ); //数据的自动完成 protected $_auto = array( //array(填充的字段,填充的内容,填充的条件,附加规则) array(‘reg_date‘,‘getDate‘,1,‘callback‘), array(‘password‘,‘md5‘,1,‘function‘), ); function getDate(){ return date(‘Y-m-d H:i:s‘); } }
(2)在/Admin/Lib/Action目录下建立UserModel.class.php相对应的控制器UserAction.class.php(代码如下):
class UserAction extends CommonAction{ function index(){ //创建模型 $user = new UserModel(); //接收查询的表单数据 $keywords = $_POST[‘keywords‘]; $type = $_POST[‘type‘]; //判断表单是否提交数据 if(!empty($keywords) && !empty($type)){ //$where = $type." like ‘%".$keywords."%‘"; //$where = $type." =".$keywords; //查询类型为id //$where[$type] = $keywords; //表达式查询 eq = ; gt > ; lt < ; neq != ; egt >= ; elt <= ; like ; (not)between; (not)in; //$where[$type] = array(‘like‘,"%".$keywords."%");//like $where[‘id‘] = array(array(gt,1),array(lt,10),‘and‘);//and 或者 or }else{ } //$list = $user->where($where)->select(); //$data = $user->where($where)->find();//只取一条数据 //$data = $user->getField(‘id,username,name,active‘); //$where[‘id‘] = array(array(gt,1),array(lt,10),‘and‘); //组合查询 //$where[‘id‘] = array(‘gt‘,1); //$where[‘name‘] = array(‘like‘,‘%a%‘); //复合查询 /*$where[‘username‘] = array(‘like‘,‘%ad%‘); $where[‘id‘] = array(‘gt‘,1); $where[‘_logic‘] = ‘or‘; $map[‘_complex‘] = $where; $map[‘active‘] = 1; //(active = 1 and (username like ‘%ad%‘ or id>1))*/ //定位查询 //$data = $user->where(‘id>0‘)->order(‘id desc‘)->getN(2);//查询前三条数据 -2 最后两条 ->first()第一条 ->last() 最后一条 top5() 前5条 //sql 直接查询 //$data = $user->query(‘select * from joys_user‘);//query:查询操作 //$data = $user->execute(‘update...delete...insert‘);//execute:增、删、改操作 //动态查询 //$data = $user->getByname(‘ad‘);//getByname中的name是数据库中的字段,动态查询只能查询一条记录 //$data = $user->count();//统计查询 //$data = $user->max(‘id‘);//获取id的最大值 //$data = $user->avg(‘id‘);//获取id的平均值 //$data = $user->sum(‘id‘);//获取id的和 //$data = $user->where($map)->select(); $list = $user->select(); $this->assign(‘ulist‘,$list); //常用的数据库操作(最常用) /*$user->select(); $user->find(); $user->getField(); $user->where(‘id=1‘)->select(); $where[‘id‘] = 1; $where[‘username‘] = array(‘like‘,‘%ad%‘); $user->where($where)->select(); $user->count(‘id‘);$user->max(‘id‘); $user->query(‘select * from XXX‘); $user->execute(‘insert update delete‘); $user->getByemail(‘[email protected]‘);*/ //连贯操作 /*$user->data(aray())->add(); $user->field(‘id,username as uname‘)->select(); $user->order(‘id desc‘)->select(); $user->order(‘id‘)->limit(5)->select(); $user->page(1,10)->select(); $user->group(‘active‘)->select(); $user->group(‘active‘)->having(‘active=1‘)->select(); $user->join(‘A on user.id=A.id‘)->select(); $user->join(‘inner join A on user.id=A.id‘)->select(); $user->join(‘right join A on user.id=A.id‘)->select(); $user->lock(true)->select();*/ $this->display(); } /* * 创建用户 */ function add(){ $this->display(); } /* * 插入数据 */ function insert(){ //创建用户模型 $user = new UserModel();//D(‘User‘) if($data = $user->create()){ //表单验证成功,要进行数据插入操作 if(false!==$user->add()){ //获取最新数据的编号(自动增长列) $userid = $user->getLastInsID(); echo ‘创建成功,用户编号是‘.$userid; }else{ echo ‘创建失败‘.$user->getDbError(); } }else{ //验证失败 echo $user->getError(); } } /* * 编辑用户 */ function edit(){ $id = $_GET[‘id‘]; if(!empty($id)){ $user = new UserModel(); $data = $user->getByid($id); $this->assign(‘data‘,$data); }else{ echo ‘请选择编辑用户‘; return false; } $this->display(); } /* * 删除操作 */ function delete(){ $deleteid = $_POST[‘deleteid‘]; //POST中删除数据的编号 //array(1) array(1,2) array(1,2,3) $deleteid = array(1,2); $id = implode(‘,‘,$deleteid);//$id = "1,2" $where = ‘id in(‘.$id.‘)‘; $user = new UserModel(); if(false!==$user->where($where)->delete()){ echo ‘删除成功‘; }else{ echo ‘删除失败‘; } } /* * 更新数据 */ function update(){ $user = new UserModel(); if($data = $user->create()){ if(!empty($data[‘id‘])){ if(false!==$user->save()){ echo ‘更新成功!‘; }else{ echo ‘更新失败‘.$user->getDbError(); } }else{ echo ‘没有更新用户的编号‘; } }else{ //验证失败 echo $user->getError(); } } }
(3)/Admin/Tpl/default/User目录下建立与控制器方法名相对应的模板文件:
add.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>创建用户</title> </head> <body> <form action="__URL__/insert" method="post"> 用户名:<input type="text" name="uname" /><br> 密码:<input type="password" name="pwd" /><br> 昵称:<input type="text" name="name" /><br> 邮箱:<input type="text" name="email" /><br> 激活:是<input type="radio" name="active" value="1" checked /> 否<input type="radio" name="active" value="0" />0<br> <input type="submit" value="保存" /> </form> </body> </html>
index.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>用户列表</title> </head> <body> <form class="__URL__/index" method="post"> 关键词:<input type="text" name="keywords" /> 类型: <select name="type"> <option value="username">用户名</option> <option value="name">昵称</option> <option value="id">ID</option> </select> <input type="submit" value="查询" /> </form> <table border="1" bordercolor="black" width="100%"> <tr><th>用户名</th><th>昵称</th><th>是否激活</th><th>ID</th></tr> <volist name="ulist" id="user"> <tr> <td><a href="__URL__/edit/id/{$user[‘id‘]}">{$user[‘username‘]}</a></td> <td>{$user[‘name‘]}</td> <td>{$user[‘active‘]}</td> <td>{$user[‘id‘]}</td> </tr> </volist> </table> </body> </html>
edit.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>编辑用户</title> </head> <body> <form action="__URL__/update" method="post"> 用户名:<input type="text" name="uname" value="{$data[‘username‘]}" /><br> 密码:<input type="password" name="pwd" /><br> 昵称:<input type="text" name="name" value="{$data[‘name‘]}" /><br> 邮箱:<input type="text" name="email" value="{$data[‘email‘]}" /><br> 激活:是<input type="radio" name="active" value="1" checked /> 否<input type="radio" name="active" value="0" />0<br> <input type="hidden" name="id" value="{$data[‘id‘]}" /> <input type="submit" value="保存" /> </form> </body> </html>
(4)访问URL:http://127.0.0.1/admin.php/User/index(add)
二、多表查询的“视图”与“关联”:
(1)新建3个表:单元表(joys_section)、分类表(joys_category)、文章表(joys_article),sql代码如下:
joys_section
CREATE TABLE `joys_section` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` VARCHAR( 255 ) NOT NULL, `alias` VARCHAR( 255 ) NOT NULL, `description` TEXT NOT NULL, `published` TINYINT( 1 ) NOT NULL DEFAULT ‘0‘, `order` INT NOT NULL DEFAULT ‘0‘, `access` TINYINT( 3 ) UNSIGNED NOT NULL DEFAULT ‘0‘, `params` TEXT NOT NULL ) ENGINE = MYISAM ;
joys_category
CREATE TABLE `joys_category`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` VARCHAR( 255 ) NOT NULL, `alias` VARCHAR( 255 ) NOT NULL, `description` TEXT NOT NULL, `published` TINYINT( 1 ) NOT NULL, `order` INT NOT NULL, `access` TINYINT( 3 ) UNSIGNED NOT NULL, `sectionid` INT UNSIGNED NOT NULL, `params` TEXT NOT NULL ) ENGINE = MYISAM ;
joys_article
CREATE TABLE `joys_article`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` VARCHAR( 255 ) NOT NULL, `alias` VARCHAR( 255 ) NOT NULL, `title_alias` VARCHAR( 255 ) NOT NULL, `introtext` MEDIUMTEXT NOT NULL, `published` TINYINT( 1 ) NOT NULL DEFAULT ‘0‘, `sectionid` INT UNSIGNED NOT NULL, `catid` INT UNSIGNED NOT NULL, `created` DATE NOT NULL, `created_by` INT UNSIGNED NOT NULL, `modified` DATETIME NOT NULL, `modified_by` INT UNSIGNED NOT NULL, `publish_up` DATETIME NOT NULL, `publish_down` DATETIME NOT NULL, `order` INT NOT NULL DEFAULT ‘0‘, `access` TINYINT( 3 ) UNSIGNED NOT NULL DEFAULT ‘0‘, `metakey` TEXT NOT NULL, `metadesc` TEXT NOT NULL, `hits` INT UNSIGNED NOT NULL, `metadata` TEXT NOT NULL, `params` TEXT NOT NULL, INDEX ( `sectionid` ), INDEX ( `catid` ), INDEX ( `created_by` ) ) ENGINE = MYISAM ;
(2)视图查询:视图只能查询,不能做增、删、改操作,但是视图的效率要不关联好。
模型CategoryViewModel.class.php
class CategoryViewModel extends ViewModel{ public $viewFields = array( ‘Category‘=>array( ‘id‘=>‘cid‘, ‘title‘=>‘ctitle‘, ‘alias‘=>‘calias‘, ‘published‘=>‘cpublished‘, ‘order‘=>‘corder‘, ‘access‘=>‘caccess‘, ‘sectionid‘, ), ‘Section‘=>array( ‘title‘=>‘sec_name‘, ‘_on‘=>‘Category.sectionid = Section.id‘, ), ‘Article‘=>array( ‘title‘=>‘art_title‘, ‘_on‘=>‘Category.id = Article.catid‘, ), ); }
控制器CategoryAction.class.php
class CategoryAction extends Action{ function index(){ //视图 $cat = new CategoryViewModel(); $list = $cat->select(); dump($list); } }
(3)关联
模型SectionModel.class.php
class SectionModel extends RelationModel{ /* * 定义关联关系 */ public $_link = array( ‘Category‘=>array( ‘mapping_type‘=>HAS_MANY,//一个单元有多个分类 ‘class_name‘=>‘Category‘, ‘foreign_key‘=>‘sectionid‘, ‘mapping_name‘=>‘categorys‘, ‘mapping_order‘=>‘sectionid desc‘, ), ‘Article‘=>array( ‘mapping_type‘=>HAS_MANY, ‘class_name‘=>‘Article‘, ‘foreign_key‘=>‘sectionid‘, ‘mapping_name‘=>‘articles‘, ), ); }
控制器SectionAction.class.php
class SectionAction extends CommonAction{ function index(){ $sec = new SectionModel(); $list = $sec->relation(true)->find(1);//select():查询出所有与section表关联的数据;relation:开启关联机制 //dump($list); //创建数据 $data[‘title‘] = ‘自定义单元1‘; $data[‘categorys‘] = array( array(‘title‘=>‘自定义分类1‘,‘alias‘=>‘test1‘,), array(‘title‘=>‘自定义分类2‘,) ); //$sec->relation(true)->add($data); //更新数据 //$sec->relation(true)->where(‘id=1‘)->save($data); //删除数据 $sec->relation(true)->delete(4); } }