Wednesday 13 November 2013

Working with Yii Create Command

Select * Query using Create Command

<?php

// Example 1:

$sql = "SELECT * FROM table WHERE col1='data' AND col2=$id";
$result = Yii::app()->db->createCommand($sql)->query();
$rowCount = $result->rowCount;

// Example 2:

$sql = "SELECT * FROM table WHERE colname = '" . $_POST['data'] . "'";
$dbCommand = Yii::app()->db->createCommand($sql);
$data = $dbCommand->queryAll();
foreach ($data as $row) {
//------
//your statement
//------
}

?>

Insert into using Create Command

<?php
Yii::app()->db->createCommand()->insert('tablename', array(
  'col1' => col1data, 
  'col2' => col2data, 
  'col3' => "col3data" //varchar datatype
));
?>

Update Query using Create Command

<?php
Yii::app()->db->createCommand
("UPDATE user SET name = $name WHERE email=:em AND id=:cid")
->bindValues(array(':em' => "test@example.com", ':cid' => $id))
->execute();
?>

Delete Query using Create Command

<?php
Yii::app()->db->createCommand()->delete('colname', 'col_id=:id', array(':id' => $id));
?>

No comments:

Post a Comment