Web Development

Most of the time, when creating SQL statements, we just need to compare strings, add strings for insertion. There are a few times when we need to use query functions.

In the Yii Framework, using CActiveRecord to insert records to a database would mean something like this:

$record = new Post();
$record->title = 'Yii Framework';
$record->description = 'awesome';
$record->save();

Having a created_at field would mean we need to save the current time it was saved. You might think of creating something like this:

$record = new Post();
$record->title = 'Yii Framework';
$record->description = 'awesome';
$record->created_at = 'NOW()';
$record->save();

But this thing doesn’t work. You would end up saving ‘NOW’ as a string. Yii Framework has the CDbExpression to solve just that.

$record = new Post();
$record->title = 'Yii Framework';
$record->description = 'awesome';
$record->created_at = new CDbExpression('NOW()');
$record->save();

There are a quite a few cases you can use CDbExpression.

Retrieving date in a certain format

$criteria = new CDbCriteria;
$criteria->select = array(new CDbExpression('DATE_FORMAT(created_at, "%Y-%m-%d"));
$posts = Post::model()->findAll($criteria);

Getting Random records

$criteria = new CDbCriteria;
$criteria->order = new CDbExpression('RAND()');
$criteria->limit = 10;
$posts = Post::model()->findAll($criteria);