先建立鏈接對象php
$connection = new \yii\db\Connection([ 'dsn' => $dsn, 'username' => $username, 'password' => $password, ]); $connection->open();
查詢返回多行:yii
$command = $connection->createCommand('SELECT * FROM post'); $posts = $command->queryAll();
返回單行:ide
$command = $connection->createCommand('SELECT * FROM post WHERE id=1'); $post = $command->queryOne();
查詢多行單值:post
$command = $connection->createCommand('SELECT title FROM post'); $titles = $command->queryColumn();
查詢標量值/計算值:ui
$command = $connection->createCommand('SELECT COUNT(*) FROM post'); $postCount = $command->queryScalar();
要養成先查文檔的習慣:
http://www.yiichina.com/doc/guide/2.0/db-daospa