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:

<?php
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:

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

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

Video tutorial:









Leave a Comment