Once you have a database connection instance, you can execute a SQL query by taking the following steps :
* Create a yii\db\Command
with a plain SQL query;
* Bind parameters (optional);
* Call one of the SQL execution methods in yii\db\Command
.
The following example shows various ways of fetching data from a database :
// return a set of rows. each row is an associative array of column names and values.
// an empty array is returned if the query returned no results
$posts = Yii::$app->db->createCommand('SELECT * FROM post')
->queryAll();
// return a single row (the first row)
// false is returned if the query has no result
$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=1')
->queryOne();
// return a single column (the first column)
// an empty array is returned if the query returned no results
$titles = Yii::$app->db->createCommand('SELECT title FROM post')
->queryColumn();
// return a scalar value
// false is returned if the query has no result
$count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM post')
->queryScalar();