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框架学习(二)的更多相关文章

  1. yii框架学习(二)

    模型 orderby的使用:->orderBy(['addtime'=>SORT_DESC, 'sort'=>SORT_ASC])->all() 在使用find()查询的时候, ...

  2. Yii框架学习笔记(二)将html前端模板整合到框架中

    选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...

  3. Yii框架学习 新手教程(一)

    本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...

  4. Struts2框架学习(二) Action

    Struts2框架学习(二) Action Struts2框架中的Action类是一个单独的javabean对象.不像Struts1中还要去继承HttpServlet,耦合度减小了. 1,流程 拦截器 ...

  5. Yii 框架学习--01 框架入门

    Yii 是一个高性能的,适用于开发 WEB2.0 应用的 PHP 框架. Yii目前有两个主要的版本: 2.0 和 1.1.本文以YII 2.0.7为例. 环境需求 Yii2.0 框架有一些系统上的需 ...

  6. PHP开发框架之YII框架学习——碾压ThinkPHP不是梦

      前  言 JRedu 程序猿是一种慵懒的生物!能少敲一行代码,绝对不会多敲一个字符!所以,越来越多的开发框架应运而生,在帮助我们完成功能的同时,极大程度上也帮我们节省了人力物力,而且也提高了系统的 ...

  7. Yii框架学习资源盘点

    盘点一些Yii框架的常用学习资源. 1.Yii中文论坛 https://www.yiichina.com/ 2.Yii中文网 http://www.yii-china.com/ 3.魏曦教你学Yii2 ...

  8. <yii 框架学习> yii 框架改为中文提示

    工作需要用到yii框架,但发现yii框架自带的提示都是英文的.上网找资料才发现其实可以自己陪置 . 将项目protected/config/main.php里的app配置加上language=> ...

  9. YII框架学习(一)

    1.安装: windows:将php命令所在的文件夹路径加入到环境变量中,通过cmd命令:进入yii框架中的framework目录,执行: php yiic webapp ../cms linux:类 ...

随机推荐

  1. OpenMP参考链接

    做个笔记. http://www.cnblogs.com/China3S/p/3500507.html

  2. JavaScript正则表达

    Javascript 与正则表达式 一.正则表达式(regular expression简称res) 1.定义: 一个正则表达式就是由普通字符以及特殊字符(称为元字符)组成的文字模式.该模式描述在查找 ...

  3. 【转载】NonEmpty和Non Empty的区别

    转载来源:http://www.ssas-info.com/analysis-services-articles/50-mdx/2196-mdx-non-empty-vs-nonempty One o ...

  4. NieR:Automata中的一段文字

    还没开始玩这个游戏,但在网易云音乐上听到一首歌,很好听 http://music.163.com/#/m/song?id=468490570 搜了一下相关视频,发现这首歌是在与一个叫做歌姬的boss战 ...

  5. Network | CIDR

    无类别(现在) 无类别域间路由(Classless Inter-Domain Routing.CIDR)是一个用于给用户分配IP地址以及在互联网上有效地路由IP数据包的对IP地址进行归类的方法. CI ...

  6. Word Pattern - LeetCode

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  7. Ubuntu 16.04安装深度的Wine(deepin-wine 1.9.0)

    说明: 1.使用的Wine版本是深度出品(Deepin),已经精简了很多没用的配置,使启动能非常快,占用资源小. 2.提取自QQ和迅雷安装包,如果安装了这个Wine不成功,可能是依赖问题,再试多几次, ...

  8. RHEL CentOS Fedora各种源介绍和安装

    CentOS默认自带CentOS-Base.repo源,但官方源中去除了很多有版权争议的软件,而且安装的软件也不是最新的稳定版.   下面介绍各种第三方软件库,以下软件库适用于与RHEL完全兼容的li ...

  9. Graphicmagick编译

    为了需求给Graphicmagick加了几个支持,版本分别为mozjpeg2.1,bzip2-1.0.6,libpng-1.6.18,libwebp-0.4.3,mozjpeg-2.1,tiff-4. ...

  10. VC++动态链接库(DLL)编程深入浅出(四)

    这是<VC++动态链接库(DLL)编程深入浅出>的第四部分,阅读本文前,请先阅读前三部分:(一).(二).(三). MFC扩展DLL的内涵为MFC的扩展,用户使用MFC扩展DLL就像使用M ...