Yii2.0实现框架增删改查

Controller

<?php

namespace frontend\controllers;

use frontend\models\User;
use yii\data\Pagination;

class UserController extends \yii\web\Controller
{
    //添加的表单页面展示
    public function actionIndex()
    {
        $model = new User();
        return $this->render(‘index‘,[‘model‘=>$model]);
    }

    //实现入库
    public function actionCreate(){
        $model = new User();
        $model->status = 1;
        $model->create_time = time();
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            //密码加密
            $model->pwd = $model->setPassword(\Yii::$app->request->post(‘User[pwd]‘));
            if($model->save()){
//                return ‘保存成功‘;
                return $this->redirect([‘user/lists‘]);
            }else{
//                \Yii::$app->getSession()->setFlash(‘error‘, ‘保存失败‘);
                return ‘保存失败‘;
            }
        }else{
            return 2;
        }
    }

    //实现列表展示
    public function actionLists(){
        //创建一个DB来获取所有的用户
        $query = User::find();
        //得到用户的总数
        $count = $query->count();
        // 使用总数来创建一个分页对象
        $pagination = new Pagination([‘totalCount‘ => $count,‘pageSize‘ => ‘2‘]);
        //实现分页数据
        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        return $this->render(‘lists‘,[‘data‘=>$users,‘pagination‘ => $pagination]);
    }

    //根据id查询当个信息
    public function actionDefault(){
        $id = \Yii::$app->request->get("id");
        $data = User::findOne($id);
        return $this->render(‘default‘,[‘data‘=>$data]);
    }

    //实现根据id进行修改
    public function actionUpd(){
        //接收参数
        $id = \Yii::$app->request->post("id");

        $model = User::findOne($id);
        if($model->load(\Yii::$app->request->post()) && $model->save()){
            return $this->redirect([‘user/lists‘]);
        }else{
            return ‘修改失败‘;
        }
    }

    //实现删除
    public function actionDel(){
        $id = \Yii::$app->request->get("id");
        $model = User::findOne($id);
        if($model->delete()){
            $this->redirect([‘user/lists‘]);
        }else{
            return ‘删除失败‘;
        }
    }

}

Model:

<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property int $id 自增id
 * @property string $username 用户名
 * @property string $pwd 密码
 * @property string $nickname
 * @property int $status
 * @property int $create_time
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return ‘user‘;
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [[‘username‘, ‘pwd‘, ‘nickname‘, ‘status‘, ‘create_time‘], ‘required‘],
            [[‘status‘, ‘create_time‘], ‘integer‘],
            [[‘username‘, ‘nickname‘], ‘string‘, ‘max‘ => 50],
            [[‘pwd‘], ‘string‘, ‘max‘ => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            ‘id‘ => ‘自增id‘,
            ‘username‘ => ‘账号‘,
            ‘pwd‘ => ‘密码‘,
            ‘nickname‘ => ‘昵称‘,
            ‘status‘ => ‘状态‘,
            ‘create_time‘ => ‘创建时间‘,
        ];
    }

    //密码加密
    public function setPassword($password){
        return Yii::$app->getSecurity()->generatePasswordHash($password);
    }
}

view文件夹下的default.php页面:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin([
    ‘action‘=>Url::to([‘user/upd‘]),
    ‘method‘=>‘post‘
]) ?>

<?= $form->field($data, ‘username‘) ?>
<?= $form->field($data,‘nickname‘) ?>
<?= $form->field($data,‘status‘)->radioList([1=>‘启用‘,2=>‘禁用‘]) ?>
<?= Html::hiddenInput("id",$data->id) ?>

<?= Html::submitButton(‘修改‘, [‘class‘ => ‘btn btn-primary‘]) ?>

<?php ActiveForm::end() ?>

view文件夹下的index.php页面:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin([
        ‘action‘=>Url::to([‘user/create‘]),
        ‘method‘=>‘post‘
]) ?>

<?= $form->field($model, ‘username‘) ?>
<?= $form->field($model, ‘pwd‘)->passwordInput() ?>
<?= $form->field($model,‘nickname‘) ?>

<?= Html::submitButton(‘添加‘, [‘class‘ => ‘btn btn-primary‘]) ?>

<?php ActiveForm::end() ?>

view文件夹下的lists.php页面:

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
use yii\helpers\Url;
?>
<table border="1">
    <tr>
        <th>ID</th>
        <th>账号</th>
        <th>密码</th>
        <th>昵称</th>
        <th>状态</th>
        <th>创建时间</th>
        <th>操作</th>
    </tr>

    <?php foreach ($data as $k => $v): ?>
    <tr>
        <td><?= Html::encode($v[‘id‘]) ?></td>
        <td><?= Html::encode($v[‘username‘]) ?></td>
        <td><?= Html::encode($v[‘pwd‘]) ?></td>
        <td><?= Html::encode($v[‘nickname‘]) ?></td>
        <td><?= Html::encode($v[‘status‘]==1 ? ‘启用‘ : ‘禁用‘) ?></td>
        <td><?= Html::encode(date("Y-m-d H:i:s",$v[‘create_time‘])) ?></td>
        <td>
            <a href="<?php echo Url::to([‘user/default‘,‘id‘=>$v[‘id‘]]) ?>">修改</a>
            <a href="<?php echo Url::to([‘user/del‘,‘id‘=>$v[‘id‘]]) ?>">删除</a>
        </td>
    </tr>
    <?php endforeach; ?>

</table>
<?= LinkPager::widget([‘pagination‘ => $pagination]) ?>

数据库:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘自增id‘,
  `username` varchar(50) NOT NULL COMMENT ‘用户名‘,
  `pwd` varchar(255) NOT NULL COMMENT ‘密码‘,
  `nickname` varchar(50) NOT NULL,
  `status` tinyint(4) NOT NULL,
  `create_time` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=58 DEFAULT CHARSET=utf8;

原文地址:https://www.cnblogs.com/hopelooking/p/10275493.html

时间: 2024-10-27 05:09:17

Yii2.0实现框架增删改查的相关文章

Yii2.0数据库操作增删改查详解

1.简单查询: one(): 根据查询结果返回查询的第一条记录. all(): 根据查询结果返回所有记录. count(): 返回记录的数量. sum(): 返回指定列的总数. average(): 返回指定列的平均值. min(): 返回指定列的最小值. max(): 返回指定列的最大值. scalar(): 返回查询结果的第一行中的第一列的值. column(): 返回查询结果中的第一列的值. exists(): 返回一个值,该值指示查询结果是否有数据. where(): 添加查询条件 wi

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现) 首先,需要知道Eclipse如何创建Dynamic Web Project for Maven,我们首先需要知道如何用Eclipse创建动态部署的Maven Web-app 项目.参考以下链接的博客:http://blog.csdn.net/smilevt/article/details/8215558. 构建完之后:实现具体的增删改查,不去部署Web war的时候我们用Junit单元测试CRUD功能.代码如

MongoDB 3.0.6 安装 增删改查

下载 安装包MSI http://yunpan.cn/cmhHdTPkXZRM2  访问密码 9b6c 上边提供的是 MongoDB 3.0.6 64Bit 的安装包 安装 如果不想直接安装在C盘..就要选择自定义安装喽.. 就是选择全部安装和自定义的那一步..全部安装是默认安装C盘的.. 我这里是安装到 D:\Program Files\MongoDB\MongoDB 的.. 需要在 D:\Program Files\MongoDB 下新建 Log 文件夹..并在Log下建立 Log.txt

6月17日 TP框架增删改查

用自动收集表单的形式进行增删改查 MainController.class.php: <?php namespace Home\Controller; use Think\Controller; class MainController extends Controller { //显示 function ShowInfo() { $model = D("Info"); $attr = $model->field("Info.Code as InfoCode,In

yii2框架增删改查案例

//解除绑定蓝牙 //http://www.520m.com.cn/api/pet/remove-binding?healthy_id=72&pet_id=100477&access-token=YWdqPCWdt3_IqkrTK-U5vS458ZWfcdeT public function actionRemoveBinding(){ $healthy_id = Yii::$app->request->get('healthy_id'); if(empty($healthy_

Laravel框架——增删改查

增: 删: 改: 查: 查询一条信息: // 通过主键获取模型... model::find(1); // 获取匹配查询条件的第一个模型... model::where('id', 1)->first(); //如果有时候你可能想要在模型找不到的时候抛出异常(如果没找到跳转到404页面) model::findOrFail(1); model::where('id','>',0)->firstOrFail(); 获取聚合:例如count.sum.max model::where('act

Hibernate框架增删改查测试类归为一个类

1 package cn.happy.test; 2 3 4 import org.hibernate.Session; 5 import org.hibernate.SessionFactory; 6 import org.hibernate.Transaction; 7 import org.hibernate.cfg.Configuration; 8 import org.junit.After; 9 import org.junit.Before; 10 import org.junit

Hibernate框架增删改查

1 package cn.happy.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 /** 8 * 1.1用于生产session对象的工具类 9 */ 10 public class HibernateUtil { 11 private static Configuration cfg=new

python 3.0 字典的增删改查

一.字典的定义方法: 1.dic = {'name':'Karen','age':22,'hobby':'girl','is_handsome':True} print(dic)    #==>{'name':'Karen'} dic = {'name':'Karen','age':22,'hobby':{'name':'xu','age':22},'is_handsome':True} 2.dic=dict((('name','Karen'),))  ||  dic=dict((['name'