How to run SQL statement in Yii ?

I would NOT like to use activerecord but run my own SQL statements using Yii, How do i do that ?

Also, what are the functions for iterating through a result set once i execute a query ?

Read the guide. -> http://www.yiiframework.com/doc/guide/

Set Following Controller where You can perform

or

May be used in View OR Model as per Your requirement

<?php

&#036;SQL=&quot;SQL Statemet&quot;


&#036;connection=Yii::app()-&gt;db; 


command=&#036;connection-&gt;createCommand(&#036;sql);


&#036;rowCount=&#036;command-&gt;execute();   // execute the non-query SQL


&#036;dataReader=&#036;command-&gt;query();   // execute a query SQL

?>

Example of a query which return an array




$list= Yii::app()->db->createCommand('select * from post')->queryAll();


$rs=array();

foreach($list as $item){

    //process each item here

    $rs[]=$item['id'];


}

return $rs;



if you want to bind some params:


$list= Yii::app()->db->createCommand('select * from post where category=:category')->bindValue('category',$category)->queryAll();

if you just want to run a query return nothing return:


Yii::app()->db->createCommand('delete * from post')->query();

Hope this help

Best regard

1 Like

@David T, Thank you very much

Thank you, your answer worked for me.