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. smtp发送邮件记得结尾发送"\r\n.\r\n"

    前段时间老板安排我修复一个邮件服务器后台C程序的bug,这个功能是邮件强制发送功能,从邮件管理后台将垃圾邮件发送出去. 因为服务器是debian系统,所以我用dbg配合日志大致跟踪后,追踪到了读取邮件 ...

  2. github 获取repo 发布的版本号

    获取最新版本 https://api.github.com/repos/nickchou/paopao/releases/latest 获取版本列表 https://api.github.com/re ...

  3. hdu 2363(枚举+最短路好题)

    Cycling Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Sub ...

  4. JS-JavaScript String 对象-string对象方法1:fromCharCode()、charCodeAt()

    1.fromCharCode(): 可接受一个指定的 Unicode 值,然后返回一个字符串. 1). 语法:String.fromCharCode(n1, n2, ..., nX)  (n1, n2 ...

  5. hihoCoder #1586 : Minimum-结构体版线段树(单点更新+区间最值求区间两数最小乘积) (ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛)

    #1586 : Minimum Time Limit:1000ms Case Time Limit:1000ms Memory Limit:256MB Description You are give ...

  6. UVA - 294 Divisors【数论/区间内约数最多的数的约数个数】

    Mathematicians love all sorts of odd properties of numbers. For instance, they consider to be an int ...

  7. 洛谷 P1328 生活大爆炸版石头剪刀布【模拟/环/周期】

    题目描述 石头剪刀布是常见的猜拳游戏:石头胜剪刀,剪刀胜布,布胜石头.如果两个人出拳一样,则不分胜负.在<生活大爆炸>第二季第8 集中出现了一种石头剪刀布的升级版游戏. 升级版游戏在传统的 ...

  8. 【java】安全加密MessageDigest的功能及用法【hash一致性算法】

    链接地址:https://blog.csdn.net/ma1kong/article/details/2662997 1.查看MessageDigest源码的注释说明 2.和hash一致性算法 什么关 ...

  9. Error Code: 1055 incompatible with sql_mode=only_full_group_by

    OperationalError at / (1055, "Expression #1 of ORDER BY clause is not in GROUP BY clause and co ...

  10. MFC中 报错:error : bitmap file Res\tankBattle.ico is not in 3.00 format

    今天换了一个ico图标,本来源图像是bmp的,让我改了后缀名成ico. 然后编译就报错了:error : bitmap file Res\tankBattle.ico is not in 3.00 f ...