Yii2数据库操作

1、使用gii创建user model 和 user controller



namespace frontend\controllers;
use app\models\User;
use yii\data\Pagination;




class MsgController extends \yii\web\Controller
{
public function actionIndex()
{
$query = User::find();
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count(),'pagesize'=>'10']);//pagesize每页显示条数
$models = $query->offset($pages->offset)->limit($pages->limit)->All();
return $this->render('index', ['models' => $models,'pages' => $pages]);
}


public function actionAdd(){
echo 'ff';
$sql = "insert into user (username) values ('ddd')";
$bool = \Yii::$app->db->createCommand($sql)->execute();
//return $this->render('add');
}


public function actionDel(){
$conn = \Yii::$app->db;
$id = \Yii::$app->request->get('id');
$command = $conn->createCommand("delete from user where id='$id'");
$command->execute();
}

public function actionUpdate(){

$connection = \Yii::$app->db;
$db=\Yii::$app->db->createCommand();
$res=$connection->createCommand()->update('user',['username' => '999','email' => '888'], ['id' => 561])->execute();
//最后一个是条件 $this->redirect('index.php?r=msg');//重定向
}

public function actionRead(){
$rows = (new \yii\db\Query())->select(['*'])->from('user')->all();
var_dump($rows);
}


}

你可能感兴趣的:(PHP)