Web Development

I have been so fascinated about how CDbCriteria worked, that I researched on the many alternate ways to search the database using the Yii Framework.

Searching one field

The search keyword will be bound by % that will equal to %{$_GET['Press']['title']}%.

$criteria=new CDbCriteria;
$criteria->addSearchCondition('title', $_GET['Press']['title']);
$presses=Press::model()->findAll($criteria);
// SELECT * FROM 'presses' 't' WHERE title LIKE :ycp0

Searching two fields

The search keyword will be bound by % that will equal to %{$_GET['Press']['title']}%.

$criteria=new CDbCriteria;
$criteria->addSearchCondition('title', $_GET['Press']['title']);
$criteria->addSearchCondition('body', $_GET['Press']['title']);
$presses=Press::model()->findAll($criteria);
// SELECT * FROM 'presses' 't' WHERE (title LIKE :ycp0) AND (body LIKE :ycp1)

Searching either two fields

The search keyword will be bound by % that will equal to %{$_GET['Press']['title']}%.

$criteria=new CDbCriteria;
$criteria->addSearchCondition('title', $_GET['Press']['title'], true, 'OR');
$criteria->addSearchCondition('body', $_GET['Press']['title'], true, 'OR');
$presses=Press::model()->findAll($criteria);
// SELECT * FROM 'presses' 't' WHERE (title LIKE :ycp0) OR (body LIKE :ycp1)

Searching either two fields using compare

The search keyword will be bound by % that will equal to %{$_GET['Press']['title']}%.

$criteria=new CDbCriteria;
$criteria->compare('title', $_GET['Press']['title'], true, 'OR');
$criteria->compare('body', $_GET['Press']['title'], true, 'OR');
$presses=Press::model()->findAll($criteria);
// SELECT * FROM 'presses' 't' WHERE (title LIKE :ycp0) OR (body LIKE :ycp1)

The Yii Framework gives us a lot of ways to search using the CDbCriteria class. Some people may say some classes seem redundant but I like how you can do things in a lot of ways.