André Castro
André Castro

Reputation: 1565

Yii2 - Connect to database inside Controller Action

Greetings,

Facts:
Database named -> acastro
Table called -> contacto
Fields in table are -> id, nome, email

I making an Yii2 application, and need to connect a highcharts chart to a table field in my database. How can i inside an action called actionAdmin connect to my database and then count the number of id's in my Contacto table stored inside acastro database.

In the old Yii1.xx i used to establish connection this way:

public function actionAdmin() {
$sql = Yii::app()->db->createCommand('
SELECT count(*) as total
FROM contacto
')->queryAll();

$total = array();

for ($i = 0; $i < sizeof($sql); $i++){
$total[] = (int) $sql[$i]["total"];
}
$this->render('admin', array('total' => $total));
}
}

The problem is that this syntax no longer works in Yii2, and i've tried the sintaxe explained in Yii2 api guide but it always give's me error of undefined variable. Here is the code that i'm using to connect acording to Yii2 api guide:

use yii\db\Command;
$total = $connection->createCommand('SELECT count (*) FROM contacto')->queryAll();

What am i doing wrong ? Any solutions ? Many thanks in advance.

Upvotes: 1

Views: 2177

Answers (2)

Pawan
Pawan

Reputation: 3864

I am not very sure that it will solve ur problem.

But in yii2 this the syntax

use app\models\Contacto; //look your Contacto Model namespace

$query = (new Query())->from('contacto');
$count = $query->count('column_name');

I hope this will help

Upvotes: 1

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

The easiest syntax in Yii2 is:

$count=(new \yii\db\Query)->from('TBL_NAME')->count('*');

It just returns the count. For example: 500

Upvotes: 1

Related Questions