yii2數據庫增刪改查詢操作

簡單的說:
1.先配置好數據庫
位置在config/db.php
更改如下:
<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=music',
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8',
];
2.新建立個models層文件這裏叫做
  位置:models/Country.php
  代碼如下:
  <?php
namespace app\models;//所有的model都要繼承這個
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{

}
3.新建controllers層文件
   <?php    
namespace app\controllers;  
use yii\web\Controller;  
use yii\data\Pagination;  //這個使用來進行分頁使用的
use app\models\Country;  //直接把model層引進來使用
 
class CountryController extends Controller  
{  
   //下面是查詢控制器的方法
   public function actionIndex()  
   {  
       $query = Country::find();  
 
       $pagination = new Pagination([  
           'defaultPageSize' => 6,  
           'totalCount' => $query->count(),  
       ]);  
 
       $countries = $query->orderBy('name')  
           ->offset($pagination->offset)  
           ->limit($pagination->limit)  
           ->all();  
 //指向跳轉位置頁面和攜帶的參數
       return $this->render('index', [  
           'countries' => $countries,  
           'pagination' => $pagination,  
       ]);  
   }




        //下面是增加數據庫的方法
        public  function actionAdd(){ 
       $ty = new Country();
       $ty->code = 'gd';
       $ty->name = 'ceshiname';
       $ty->population = '10010';
       if(($ty->save())>0){
           echo "添加ok"; 
       }else{ 
           echo "fail";
       }
        }


       //下面是刪除的方法
public  function  actionDel(){ 
       $tydel = new Country();
       $success =  $tydel->deleteAll('name ="ceshiname"');
       if($success>0){echo "刪除成功"; }else{echo "刪除失敗"; } 
   }




   //下面是修改方法
   public  function actionUpdate(){ 
       $tyupdate = new Country();
       $kkk = $tyupdate->updateAll(array('code'=>'mH'),'code="CH"');
       if($kkk>0){ 
           echo "update success!";
       }else{ 
           echo "update fail";
       }


   }




}   
 4.建立展現層
   位置views/country/index.php
   代碼如下:
   <?php  
use yii\helpers\Html;  
use yii\widgets\LinkPager;  
?>  
<h1>Countries</h1>  
<ul>  
<?php foreach ($countries as $country): ?>  
   <li>  
       <?= Html::encode("{$country->name} from ({$country->code})") ?>:  
       <?= $country->population ?>  
   </li>  
<?php endforeach; ?>  
</ul>  
 
<?= LinkPager::widget(['pagination' => $pagination]) ?>  
說明:name與code都是數據庫中存在的字段
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章