Yii2 增删改查 搜索 分页 文件上传

知识点梳理 

User::find()->all();    //返回所有用户数据;
User::findOne($id);   //返回 主键 id=1  的一条数据; 
User::find()->where(['name' => 'ttt'])->one();   //返回 ['name' => 'ttt'] 的一条数据;
User::find()->where(['name' => 'ttt'])->all();   //返回 ['name' => 'ttt'] 的所有数据;
User::findBySql('SELECT * FROM user')->all();  //用 sql  语句查询 user 表里面的所有数据;
User::findBySql('SELECT * FROM user')->one();  此方法是用 sql  语句查询 user 表里面的一条数据;
User::find()->andWhere(['sex' => '女', 'age' => '18'])->count('id');   //统计符合条件的总条数;
User::find()->one();    //返回一条数据;
User::find()->all();    //返回所有数据;
User::find()->count();    //返回记录的数量;
User::find()->average();   //返回指定列的平均值;
User::find()->min();    //返回指定列的最小值 ;
User::find()->max();   //返回指定列的最大值 ;
User::find()->scalar();    //返回值的第一行第一列的查询结果;
User::find()->column();    //返回查询结果中的第一列的值;
User::find()->exists();    //返回一个值指示是否包含查询结果的数据行;

查询操作:

User::find()->where(['name' => 'username'])->one();   此方法返回 ['name' => 'username'] 的一条数据;
User::find()->where(['name' => 'username'])->all();   此方法返回 ['name' => 'username'] 的所有数据;

User::find()->andWhere(['sex' => '男', 'age' => '24'])->count('id');   统计符合条件的总条数;

新增操作:

$model = newUser();
$model->username = 'username';
$model->age      = '20';
$model->insert();

修改操作:
$User = User::findOne($id);
$User->name = 'zhangsan';
$User->save(); // 等同于 $User->update();

删除操作:

User::deleteAll('name = username');    删除 name = username 的数据;
User::findOne($id)->delete(); 删除主键为 $id变量 值的数据库
User::deleteAll('age > :age AND sex = :sex', [':age' => '20', ':sex' => '1']);  删除符合条件的数据;

模糊查询:

  ->where(["like","字段名","要搜索的值"]) ;

文件上传: 

 $image=UploadedFile::getInstanceByName('img');     ( img是input里的name的值   <input type="file" name="img"> )

//路径           文件的临时位置
$path = Yii::$app->basePath.'\web\uploads\\';

//图片的名   加密                      获取名字                        获取后缀
$filename = md5($image->getBaseName()).'.'.$image->getExtension();     
(为了得到这样的图片名称  0e85820f65d10eee187ba6b24295e46b.gif )

//移动文件     路径+文件名=要移动的位置
$image->saveAs($path.$filename);

分页:

下面的例子中有方法:在方法actionList中,这个方法和搜索写在了一起

表单  (后缀为.php)

<?php

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表单添加页面</title>
</head>
<body>
<center>
<form action="?r=xinxi/add" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>用户名</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="pwd"></td>
        </tr>
        <tr>
            <td>邮件</td>
            <td><input type="text" name="email"></td>
        </tr>
        <tr>
            <td>头像</td>
            <td><input type="file" name="img"></td>
        </tr>
        <tr>
            <!-- 必须写的   写了这个才能用写这个表单-->
            <td><input name="_csrf" type="hidden" value="<?= Yii::$app->request->csrfToken ?>"></td>
            <td><input type="submit" value="提交"></td>
        </tr>
    </table>
</form>
</center>
</body>
</html>

控制器 

<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use app\models\Xinxi;
use yii\data\Pagination;


class XinxiController extends Controller
{
    /**
     * @return string
     * 文件上传+数据入库
     */
    public function actionAdd(){
        //接收的数据
        $postData = Yii::$app->request->post();
        if(!$postData)
        {
            return $this->render("form");
        }
        //接收用户名
       $name =  $postData['name'];
        //接收密码
       $pwd =  $postData['pwd'];
       //接收邮件
       $email =  $postData['email'];
       //接收上传的文件数组
        $image=UploadedFile::getInstanceByName('img');
        //路径           文件的临时位置
        $path = Yii::$app->basePath.'\web\uploads\\';
        //图片的名                名字                       后缀
        $filename = md5($image->getBaseName()).'.'.$image->getExtension();
        //移动文件          路径+文件名=要移动的位置
        $image->saveAs($path.$filename);
        //入库
//        $res=Yii::$app->db->createCommand()->batchInsert(Xinxi::tableName(), ['name','pwd','email','img'], [["$name","$pwd","$email","$filename "]])->execute();
        $model = new Xinxi();
        $model->name = $name;
        $model->pwd = $pwd;
        $model->email = $email;
        //不能有关键字(表中)
        $model->pp = $filename;
        $res= $model->save();
        if($res){
            echo "<script>alert('添加成功');location.href='?r=xinxi/list'</script>";
        }else{
            echo "<script>alert('添加失败');</script>";
        }
    }


    /**
     * @return string
     * 展示的数据
     */
    public function actionList(){
        //实例化
        $query = Xinxi::find();
        //接收到的值  要搜索的值
        $sel = Yii::$app->request->get('sel');
        //分页
       $pagination = new Pagination([
                       'defaultPageSize' => 2,
           'totalCount' => $query->where(["like","name","$sel"])->count(),
        ]);

       $countries = $query->orderBy('id')
           //模糊查询
           ->where(["like","name","$sel"])
           ->offset($pagination->offset)
           ->limit($pagination->limit)
          ->all();

       return $this->render('list', [
                     'countries' => $countries,
           'pagination' => $pagination,
        ]);
    }

    /**
     * 删除
     */
    public function actionDel(){
        $id = Yii::$app->request->get('id');
        $res=Xinxi::findOne($id)->delete();
        if($res){
            echo "<script>alert('删除成功');location.href='?r=xinxi/list'</script>";
        }
    }

    public function actionUpd(){
        $postData = Yii::$app->request->post('id');
        if(!$postData)
        {
            $id = Yii::$app->request->get('id');
            $data=Xinxi::findOne($id);   //返回 主键 id=1  的一条数据;
            return $this->render("upd",['arr'=>$data]);
        }else{
            $model = new Xinxi();
            //接收到的所有数据
            $data = Yii::$app->request->post();
            //移除_csrf 的参数  因为它不需要入库
            unset($data['_csrf']);

            //接收上传的文件数组
            $image=UploadedFile::getInstanceByName('img');
            //路径           文件的临时位置
            $path = Yii::$app->basePath.'\web\uploads\\';
            //图片的名                名字                       后缀
            $filename = md5($image->getBaseName()).'.'.$image->getExtension();
            //移动文件          路径+文件名=要移动的位置
            $image->saveAs($path.$filename);

            $id = $data['id'];
            $data['pp']=$filename;
            $res= $model->updateAll($data,"id=$id");
            if($res){
                echo "<script>alert('修改成功');location.href='?r=xinxi/list'</script>";
            }else{
                echo "<script>alert('修改失败');location.href='?r=xinxi/list'</script>";
            }
        }
    }
}

模板 继承的 ActiveRecord是为了 数据库的操作

<?php
namespace app\models;
use yii\db\ActiveRecord;
class Xinxi extends ActiveRecord
{

}

列表的样式是用的Bootstrap(你要是没有Bootstrap类包,可以把 head头中的link和script 去掉  table和的class去掉 ) 

列表中搜索的form中写了 <input type="hidden" name="r" value="xinxi/list">  是为了找到?=xinxi/list方法为了跳转页面

列表烈面 (后缀为.php) 

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;

?>

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <link href="/bootstrap/css/bootstrap.min.css">
        <script src="/scripts/jquery.min.js"></script>
        <script src="/bootstrap/js/bootstrap.min.js"></script>

    </head>
    <body>
    <center>
        <form action="?r=xinxi/list" method="get">
            <input type="text" name="sel" >
            <input type="hidden" name="r" value="xinxi/list">
            <input type="submit" value="搜索" class="btn btn-default">
        </form>
        <table  border="1" class="table table-hover">
            <tr>
                <td>编号</td>
                <td>用户名</td>
                <td>邮箱</td>
                <td>头像</td>
                <td>操作</td>
            </tr>
            <?php foreach ($countries as $v){?>
                <tr>
                    <!-- 像id这样的也是一种方法-->
                    <td><?= $v->id ?></td>
                    <td><?php echo $v['name']?></td>
                    <td><?php echo $v['email']?></td>
                    <td><img src="\uploads\<?php echo $v['pp']?>" style="width: 100px;height: 70px;"></td>
                    <td>
                        <a href="?r=xinxi/del&id=<?php echo $v['id']?>">删除</a> |
                        <a href="?r=xinxi/upd&id=<?= $v->id ?>">修改</a> |
                        <a href="?r=xinxi/add">添加</a>
                    </td>
                </tr>
            <?php }?>
        </table>
        <?= LinkPager::widget(['pagination' => $pagination]) ?>
    </center>

    </body>
    </html>

修改页面 (后缀为.php)

<?php

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表单添加页面</title>
</head>
<body>
<center>
<form action="?r=xinxi/upd" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>用户名</td>
            <td><input type="text" name="name" value="<?php echo  $arr['name']?>"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="pwd" value="<?= $arr->pwd ?>"></td>
        </tr>
        <tr>
            <td>邮件</td>
            <td><input type="text" name="email" value="<?= $arr->email ?>"></td>
        </tr>
        <tr>
            <td>头像</td>
            <td><input type="file" name="img"><img src="\uploads\<?= $arr->pp ?>" style="width: 100px;height: 70px;"></td>
        </tr>
        <tr>
            <td><input name="_csrf" type="hidden" value="<?= Yii::$app->request->csrfToken ?>"></td>
            <td>
                <input type="submit" value="提交">
                <input type="hidden" name="id" value="<?= $arr->id?>">
            </td>
        </tr>
    </table>
</form>
</center>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/baiyawen1/article/details/83719750