This is a post I’ve wanted to write for a long time, perhaps it will be useful to others. It’s about using Zend_Db_Table_Select and the SQL LIKE statement. I remember it giving me some headaches in the past, so here it is:

The problem is that Zend’s implementation is a bit counterintuitive, as the % sign is part of the query – as it has a special significance in SQL – and not of the string being search. So the first thing in my mind was:

PHP

1

2

3

4

5

6

7

8

9

10

My_Table_ExampleextendsZend_Db_Table

{

publicfunctionsearch($value)

{

$select=$this->select();

$select->where('column LIKE ?%',$value);

// ...

}

}

Which doesn’t quite work. Of course, one can always use good ol’ string concatenation, do it like this:

PHP

1

2

3

4

5

6

7

8

9

10

My_Table_ExampleextendsZend_Db_Table

{

publicfunctionsearch($value)

{

$select=$this->select();

$select->where('column LIKE "'.$value.'%"');

// ...

}

}

…and risk an SQL Injection attack. Definitely not the best approach! In the end I found the best solution to do it is:

PHP

1

2

3

4

5

6

7

8

9

10

My_Table_ExampleextendsZend_Db_Table

{

publicfunctionsearch($value)

{

$select=$this->select();

$select->where($this->_db->quoteInto('column LIKE ?',$value.'%'));

// ...

}

}

…which, as previously stated, it’s quite counterintuitive. But hey, it works 🙂