Yii框架增刪改查


namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class ZsgcController extends Controller

{

//關閉csrf攻擊

    public $enableCsrfValidation=false;
    /**
     * @inheritdoc

     */

//展示添加頁面

    public function actionZsgc()
    {
        return $this->render('add');

    }

//執行添加

        public function actionForm(){
    
        $arr = $_POST;
         // var_dump($arr);die;
           $db = Yii::$app->db;  
        $data=$db->createCommand()->insert('zsgc',$arr)->execute();   
         if($data){  
            echo "<script>alert('添加成功')</script>";  
            //添加成功跳轉到我們的展示頁面(show)  
            $this->redirect('index.php?r=zsgc/show');  
        }else{  
            echo "添加失敗";
             $this->redirect('index.php?r=zsgc/add');  

        }  
     

    }

//執行展示頁面

    public function actionShow()
    {
           $db = Yii::$app->db;  
            $sql="SELECT * FROM zsgc";  
           $arr = $db->createCommand($sql)->queryAll();
           //print_r($arr);die;  
            return $this->render('show',['data'=>$arr]);  

    }

//執行刪除

    public function actionDelete(){

         //接id;
        $id=$_GET['id'];
         // print_r($id);die;
     $result=Yii::$app->db->createCommand()->delete('zsgc', "id =$id")->execute();
     //print_r($res);die;
       if($result){  
            echo "<script>alert('刪除成功')</script>";  
            //添加成功跳轉到我們的展示頁面(lists)  

            $this->redirect('index.php?r=zsgc/show');  
        }else{  
            echo "刪除失敗";
             $this->redirect('index.php?r=zsgc/show');  

        }  

    }

//通過id要修改的頁面

   public function actionUpdate(){
        $id=$_GET['id'];
        // echo $id;die;
     $command = \Yii::$app->db->createCommand("SELECT * FROM zsgc WHERE id=$id");
     $post = $command->queryOne();
      return $this->render('update',['list'=>$post]);

    }

//執行修改

    public function actionUp(){
     $data=$_POST;
     // print_r($data);die;

    $res = \Yii::$app->db->createCommand()->update('zsgc', $data,["id" => $data['id']])->execute();
    // print_r($res);
   
     if($res){  
            echo "<script>alert('修改成功')</script>";  
            //添加成功跳轉到我們的展示頁面(lists)  
            $this->redirect('index.php?r=zsgc/show');  
        }else{  
            echo "修改失敗";
             $this->redirect('index.php?r=zsgc/show');  

        }  

        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章