Executing a SQL without calling a Model in Yii framework

Recently I have started working on Yii framwork. This framework has really inspired me because of the architecture of its model and above all “Gii”, the model generator. It’s now quite easy to call your DB queries via models in Yii without even writing long SQL.

But still there is a room to implement your custom or complex SQL which cannot be fit in your models. Below is a small code that can execute your sql via its DB connection and can return you result in an array.

Here is a small one:

$connection=Yii::app()->db;
$sql = "SELECT id,username FROM users";
$command = $connection->createCommand($sql);            
$dataReader=$command->query();          
$rows=$dataReader->readAll();
print_r($rows);

This above code will call the Yii DB connection and execute a SQL. The result can be fatched by “readAll” or only “read” if you want a single row.

I will be posting some more code from Yii in later posts.



Tags: , , , , , , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by Wordpress. Design: Supermodne.
CCTV Distributor in Pakistan