Despite all the implications of using LIKE in MySQL, sometimes it’s quite useful for a proof-of-concept to be able to use it.
Even though this is a rather trivial example, I hope it will be of help to whoever is wondering how to use a LIKE in a where using a Zend_Db_Select::where() or Zend_Db_Select::orWhere() and did not manage to find decent documentation about it.
<?php
class Default_Model_FooBar extends Zend_Db_Table_Abstract
{
/**
* Local table name
*
* @var string $_name The name of the table associated with
* this model class.
*/
protected $_name = ‘foobar’;
/**
* Get Foo.
*
* This method does absolutely nothing real but
* would fetch “foo” using a like.
*
* @param string $bar The string to search like.
* @return array An array of results or false.
*/
public function getFoo($bar)
{
$select = $this->getSelect();
// Magic is here!
$select->where(‘t.foo LIKE ?’, $bar . ‘%’);
return $this->getAdapter()->query($select)->fetchAll();
}
/**
* Get Foo OR bar.
*
* This method does absolutely nothing real but
* would fetch “foo” or “bar” using a like cond.
*
* @param string $bar The string to search like.
* @return array An array of results or false.
*/
public function getFooBar($bar)
{
$select = $this->getSelect();
// Magic is here!
$select->where(‘t.foo LIKE ?’, $bar . ‘%’);
$select->orWhere(‘t.bar LIKE ?’, $bar . ‘%’);
return $this->getAdapter()->query($select)->fetchAll();
}
/**
* Get a select
*
* Simple method to construct a common select and return it.
*
* @return Zend_Db_Select $select The select object.
*/
protected function getSelect()
{
$select = $this->getAdapter()->select();
$select->from(
‘t’ => $this->_name, array(‘fields’, ‘I’, ‘want’)
);
return $select;
}
As you can see, we bind a parameter to the where() method using the ? symbol, then when assigning the value of this parameter — second parameter — we append the wildcard character %.
The new binded parameter value is then string% and which gets quoted and executed giving you the expected output.







