Run an arbitrary SQL command from within Yii

Run an arbitrary SQL command from within Yii

Last updated:

completely arbitrary SQL query

$result = Yii::app()->db->createCommand("select e.name from users u where u.surname='smith'")->queryAll();

arbitrary SQL query with parameter binding

(to avoid SQL Injection)

$sql = "select * from users u where u.id =  :var ";
$command = Yii::app()->db->createCommand($sql);
$command->bindParam(':var',$_POST['id']); //it's safe
$result = $command->queryAll();

using the query builder

$result = Yii::app()->db->createCommand()
                        ->select('name')
                        ->from('users')
                        ->where("surname='smith'")
                        ->queryAll();