How to use mysql query in Yii 2.0 Framework

Today I will explain to you how you can use sql queries in Yii 2.0 Framework.

In Yii 2.0 Framework you can use Sql queries with findBySql() function.

For example, I have a table called Country, to extract data from my table, I will create a new model with this code:

namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord


Next, I will add new action in my Controller:

public function actionEntry()

$country = Country::findBySql('SELECT * FROM country')->all();
return $this->render('entry', [
'countries' => $country,

And in my view file I will add this code:

use yii\helpers\Html;
use yii\widgets\LinkPager;
<?php foreach ($countries as $country): ?>
<?= Html::encode("{$country->name} ({$country->code})") ?>:
<?= $country->population ?>
<?php endforeach; ?>

In this way I will extract all data from my table.

Video tutorial:

Leave a Comment