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:类 ...
随机推荐
- pyqt线程实现
# coding=utf-8 __author__ = 'a359680405' from PyQt5.QtCore import * from PyQt5.QtGui import * from P ...
- Delphi 半透明窗体,窗体以及控件透明度
很简单了 现在,适用所有控件和窗体: delphi设置窗口透明 form1.AlphaBlend :=true; //透明form1.AlphaBlendValue :=180; //透明度form1 ...
- cisco packet 实验教程(二)
06. 三层交换机实现VLAN间路由 技术原理 1)三层交换机是带有三层路由功能的交换机,也就是这台交换机的端口既有三层路由功能,也具有二层交换功能.三层交换机端口默认为二层口,如果需要启用三层功能就 ...
- LeetCode OJ-- Letter Combinations of a Phone Number ***
https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ 使用递归,深搜,使用 map 保存已经处理过的结果 cl ...
- springBoot AOP环绕增强、自定义注解、log4j2、MDC
(一)log4j2 maven配置 <dependency> <groupId>org.springframework.boot</groupId> <art ...
- UITextView只能显示两行问题
需求:UITextView只能显示两行 UITextView * textView = [[UITextView alloc]init]; textView.frame = CGRectMake(20 ...
- ()centos6.8安装配置ftp服务器
ftp传输原理 客户端通过某软件用某个端口(a端口)向服务端发起tcp连接请求,同时告诉服务端客户端另一个空闲端口号(b端口),服务端用21端口与客户端建立一条控制连接通道. 接着在默认情况下,服务端 ...
- usaco-Subset Sums
题意: 给出一个1-n的数列,求把它分为两组数使得两组数的和相等的方案数. 分析: 如果可能分成两组,那么(n+1)n/2一定为偶数,且n%4=2或3.可以设dp[i][j]表示从1-i中的数拼出的方 ...
- BZOJ 3672 NOI 2014 购票
题面 Description 今年夏天,NOI在SZ市迎来了她30周岁的生日.来自全国 n 个城市的OIer们都会从各地出发,到SZ市参加这次盛会. 全国的城市构成了一棵以SZ市为根的有根树,每个城市 ...
- Android 监听双卡信号强度(附完整代码)
Android 监听双卡信号强度 监听单卡信号强度 监听单卡的信号强度非常简单直接用TelephonyManager.listen()去监听sim卡的信号强度. TelephonyManager = ...