Yii2增删改查

Controller

Yii2增删改查
<?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 '删除失败';
        }
    }

}
Yii2增删改查

Model:

Yii2增删改查
<?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);
    }
}
Yii2增删改查

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

Yii2增删改查
<?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() ?>
Yii2增删改查

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

Yii2增删改查
<?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() ?>
Yii2增删改查

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

Yii2增删改查
<?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]) ?>
Yii2增删改查

数据库:

Yii2增删改查
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;
Yii2增删改查
上一篇:spring后置处理器BeanPostProcessor


下一篇:C#中的可空类型