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. 判断图连通的三种方法——dfs,bfs,并查集

    Description 如果无向图G每对顶点v和w都有从v到w的路径,那么称无向图G是连通的.现在给定一张无向图,判断它是否是连通的. Input 第一行有2个整数n和m(0 < n,m < ...

  2. linux文本处理常用命令

    linux文本处理常用命令   linux文本处理命令:grep.sed.printf.awk 1.grep grep的作用是按行查找字符,输出包含字符的行. #从文件查询 grep 'hello' ...

  3. 树的直径新求法、codeforces 690C3 Brain Network (hard)

    树的直径新求法 讲解题目 今天考了一道题目,下面的思路二是我在考场上原创,好像没人想到这种做法,最原始的题目,考场上的题目是这样的: 你现在有1 个节点,他的标号为1,每次加入一个节点,第i 次加入的 ...

  4. delphi中如何将string类型的字符串数据转化成byte[]字节数组类型的数据

    var  S:String;  P:PChar;  B:array of Byte;begin  S:='Hello';  SetLength(B,Length(S)+1);  P:=PChar(S) ...

  5. js判断是否是PC,IOS,Android客户端

    写在前面 在项目中使用html5,需要针对不同的客户端浏览器有不一样的处理方式,这就需要对请求中的useragent进行分析,并进行处理. 一个例子 <%@ Page Language=&quo ...

  6. 线程安全的单例模式还需要对成员变量的set get方法设置锁么

    不需要,线程安全的单例模式,在获得对象时已经加锁了,保证每时每刻只有一个线程获得此单例对象.所以不需要再上锁了啊

  7. PHP使用frameset制作后台界面时,怎样实现通过操作左边框架,使右边框架中的页面跳转?

    左框架的链接,不仅要指定链接的文件名,还需要通过 target 属性指定要打开的目标框架名(即楼主要求的右框架名). 例:假设右框架为 <frame scr="lx1.htm" ...

  8. Tomcat 性能监控及调优

    1.性能监控 方式1: /usr/local/tomcat7/conf/tomcat-users.xml 添加如下: <role rolename="manager-gui" ...

  9. Iowait的成因、对系统影响及对策

    什么是iowait?顾名思义,就是系统因为io导致的进程wait.再深一点讲就是:这时候系统在做io,导致没有进程在干活,cpu在执行idle进程空转,所以说iowait的产生要满足两个条件,一是进程 ...

  10. 防止vue组件渲染不更新

    1.key <el-dialog title="" :visible.sync="dialogVisible" @close="dialogCl ...