YII框架学习(二)
YII框架的增删改查
例:一个新闻表的增删改查:
(1)首先使用gii工具生成控制器和模型
(2)控制器
<?php class NewsController extends Controller
{
public $layout = false; //查询
public function actionIndex()
{ //获取根目录
//echo Yii::app()->baseUrl ;die;
//获取当前控制器路径
//echo Yii::app()->request->url;die;
//方式一:
//多个条件查要用and连接
//$n=News::model()->find("title=:title and slug=:slug",array(":title"=>'234',":slug"=>'234'));
//var_dump($n->text);die;
//方式二:
$criteria = new CDbCriteria();
$criteria->order = 'id desc';
//计算总数
$count = News::model()->count($criteria);
$pager = new CPagination($count);
//设置页大小
$pager->pageSize = 4;
$pager->applyLimit($criteria);
$news = News::model()->findAll($criteria);
//获取当前页
$num = Yii::app()->request->getParam('page')?Yii::app()->request->getParam('page'):1;
$data['news'] = $news;
$data['pages'] = $pager;
//分配当前页起始编号
$data['num'] = ($num-1)*$pager->pageSize;
//将变量分配到模板
$this->render('index',$data);
} //新增数据
public function actionAdd(){
//新增时要new
$newsModel = new News();
//设置初始值,避免报错
$info->id = '';
$info->title = '';
$info->text = '';
if(!empty($_POST)){
$newsModel->title = $_POST['title'];
$newsModel->text = $_POST['text'];
$newsModel->slug = 'aa';
//判断更新还是新增
if(!empty($_POST['id'])){
//更新
$res = News::model()->updateByPk($_POST['id'], array('title'=>$_POST['title'],'text'=>$_POST['text']));
if($res){
$this->redirect(array('index'));
}else{
$info = News::model()->findByPk($_POST['id']);
$data['info'] = $info;
}
}else{
//新增
// $res = News::model()->newsAdd($_POST['title'],$_POST['text'], '123test');
if($newsModel->save()){
$this->redirect(array('index'));
}
} }else{
//获取GET/POST传过来的参数
$id = Yii::app()->request->getParam('id');
if(!empty($id)){
$info = News::model()->findByPk($id);
$data['info'] = $info;
}
}
$this->render('add', $data);
} //删除
public function actionDel(){
$id = Yii::app()->request->getParam('id');
$res= News::model()->findByPk($id)->delete(); // 假设有一个帖子,其 ID 为 10
$this->redirect(array('index'));
}
(3)模型(gii生成的)
<?php /**
* This is the model class for table "news".
*
* The followings are the available columns in table 'news':
* @property integer $id
* @property string $title
* @property string $slug
* @property string $text
*/
class News extends CActiveRecord
{
public $attributes;
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return News the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
} /**
* @return string the associated database table name
*/
public function tableName()
{
return 'news';
} /**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, slug, text', 'required'),
array('title, slug', 'length', 'max'=>128),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, title, slug, text', 'safe', 'on'=>'search'),
);
} /**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
} /**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'title' => 'Title',
'slug' => 'Slug',
'text' => 'Text',
);
} /**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('slug',$this->slug,true);
$criteria->compare('text',$this->text,true); return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
(4)视图:
index.php
<table>
<tr>
<th>编号</th>
<th>标题</th>
<th>内容</th>
<th>操作</th>
</tr>
<?php
$i = $num;
foreach($news as $val){
$i++;
?>
<tr>
<td><?= $i?></td>
<td><?= $val->title?></td>
<td><?= $val->text?></td>
<td><a href="<?= $this->createUrl('add', array('id' => $val->id))?>">编辑</a> <a href="<?= $this->createUrl('del',array('id'=>$val->id))?>">删除</a></td>
</tr>
<?php
}
?>
<tr><td colspan="4">
<?php
$this->widget('CLinkPager',array(
'header'=>'',
'firstPageLabel' => '首页',
'lastPageLabel' => '末页',
'prevPageLabel' => '上一页',
'nextPageLabel' => '下一页',
'pages' => $pages,
'maxButtonCount'=>13
)
);
?>
</td></tr>
</table>
add.php
<h3>添加</h3>
<form method="post" action="">
标题:<input type="text" name="title" value="<?= $info->title?>"><br>
内容:<textarea rows="5" cols="10" name="text"><?= $info->text ?></textarea><br>
<input type="submit" name="sub" value="提交">
<input type="hidden" name="id" value="<?= $info->id?>">
</form>
YII框架学习(二)的更多相关文章
- yii框架学习(二)
模型 orderby的使用:->orderBy(['addtime'=>SORT_DESC, 'sort'=>SORT_ASC])->all() 在使用find()查询的时候, ...
- Yii框架学习笔记(二)将html前端模板整合到框架中
选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...
- Yii框架学习 新手教程(一)
本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...
- Struts2框架学习(二) Action
Struts2框架学习(二) Action Struts2框架中的Action类是一个单独的javabean对象.不像Struts1中还要去继承HttpServlet,耦合度减小了. 1,流程 拦截器 ...
- Yii 框架学习--01 框架入门
Yii 是一个高性能的,适用于开发 WEB2.0 应用的 PHP 框架. Yii目前有两个主要的版本: 2.0 和 1.1.本文以YII 2.0.7为例. 环境需求 Yii2.0 框架有一些系统上的需 ...
- PHP开发框架之YII框架学习——碾压ThinkPHP不是梦
前 言 JRedu 程序猿是一种慵懒的生物!能少敲一行代码,绝对不会多敲一个字符!所以,越来越多的开发框架应运而生,在帮助我们完成功能的同时,极大程度上也帮我们节省了人力物力,而且也提高了系统的 ...
- Yii框架学习资源盘点
盘点一些Yii框架的常用学习资源. 1.Yii中文论坛 https://www.yiichina.com/ 2.Yii中文网 http://www.yii-china.com/ 3.魏曦教你学Yii2 ...
- <yii 框架学习> yii 框架改为中文提示
工作需要用到yii框架,但发现yii框架自带的提示都是英文的.上网找资料才发现其实可以自己陪置 . 将项目protected/config/main.php里的app配置加上language=> ...
- YII框架学习(一)
1.安装: windows:将php命令所在的文件夹路径加入到环境变量中,通过cmd命令:进入yii框架中的framework目录,执行: php yiic webapp ../cms linux:类 ...
随机推荐
- C#图解教程学习笔记——委托
一.委托概述委托和类一样,是用户自定义类型,也是引用类型.但类表示的是数据和方法的集合,而委托持有一个或多个方法,以及一系列预定义操作. 可以通过以下操作步骤来使用委托:(1)声明一个委托类型.委托声 ...
- Django性能调优
1.针对数据库的调优 程序对数据库的多次访问,会影响速度. 一般的流程是建立连接,获取或者修改数据,关闭连接.如果多次请求,导致多次建立连接会影响到速度. 解决办法有:1.延长连接时间并执行多次操作 ...
- luogu P1579 哥德巴赫猜想(升级版)
题目描述 一个等差数列是一个能表示成a, a+b, a+2b,..., a+nb (n=0,1,2,3,...)的数列. 在这个问题中a是一个非负的整数,b是正整数.写一个程序来找出在双平方数集合(双 ...
- bzoj 4465: [Jsoi2013]游戏中的学问
4465: [Jsoi2013]游戏中的学问 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 121 Solved: 59[Submit][Statu ...
- php中for与foreach对比
总体来说,如果数据库过几十万了,才能看出来快一点还是慢一点,如果低于10万的循环,就不用测试了.php推荐用foreach.循环数字数组时,for需要事先count($arr)计算数组长度,需要引入自 ...
- window环境下使用PHP OpenSSL扩展函数返回false的原因
window环境下使用PHP OpenSSL扩展函数返回false的原因(openssl_pkey_new) 使用的开发环境是PHPstudy ,在使用OpenSSL的函数openssl_pkey_n ...
- Java中获取当前时间并格式化
主要有两种方式,其中使用Date比较好控制,代码如下: //使用Calendar Calendar now = Calendar.getInstance(); System.out.println(& ...
- mfoc安装编译
系统环境 UBUNTU16.04,要安装好各种基础的编译环境,这就不说了,如果不知道需要什么,那就编译时出错时看到什么安装什么吧 下载源码包libnfc, mfoc, mfcuk,都是github上, ...
- 深入浅出 Cocoa 之 Core Data(1)- 框架详解
深入浅出 Cocoa 之 Core Data(1)- 框架详解 罗朝辉(http://blog.csdn.net/kesalin) CC 许可,转载请注明出处 Core data 是 Cocoa 中处 ...
- 【spring cloud】对接口调用者提供API使用的安全验证微服务【这里仅通过代码展示一种设计思想】【后续可以加入redis限流的功能,某段时间某个IP可以访问API几次】
场景: 公司的微服务集群,有些API 会对外提供接口,供其他厂商进行调用.这些公开的API接口,由一个OpenAPI微服务统一提供给大家. 那么所有的调用者在调用公开API接口的时候,需要验证是否有权 ...