title: Yii2 - Connect to database inside Controller Action
body: <p><strong>Greetings,</strong></p>
  
  <pre><code>Facts:
  Database named -&gt; acastro
  Table called -&gt; contacto
  Fields in table are -&gt; id, nome, email
  </code></pre>
  
  <p><strong>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.</strong></p>
  
  <p>In the old Yii1.xx i used to establish connection this way:</p>
  
  <pre><code>public function actionAdmin() {
  $sql = Yii::app()-&gt;db-&gt;createCommand('
  SELECT count(*) as total
  FROM contacto
  ')-&gt;queryAll();
  
  $total = array();
  
  for ($i = 0; $i &lt; sizeof($sql); $i++){
  $total[] = (int) $sql[$i]["total"];
  }
  $this-&gt;render('admin', array('total' =&gt; $total));
  }
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>use yii\db\Command;
  $total = $connection-&gt;createCommand('SELECT count (*) FROM contacto')-&gt;queryAll();
  </code></pre>
  
  <p><strong>What am i doing wrong ? Any solutions ?
  Many thanks in advance.</strong></p>