Search code examples
phpzend-frameworkmysql-error-1054

Order clause with 'like' clause in Zend DB


Query:

select * from table_name ORDER BY name like 'C%' DESC;

This query work fine in MySql, but i am unable build the query using Zend DB. I am getting error while executing.

PHP DB code:

$result = $this->getDefaultAdapter() ->select() ->from($this->_name,array('*')) ->order("name like 'C%' DESC") ->query() ->fetchAll();

Error:

Column not found: 1054 Unknown column 'name like 'C%'' in 'order clause' 

Thanks in advance


Solution

  • Zend_Db_Select tries to delimit strings as column names, but it skips doing that if you pass an object of type Zend_Db_Expr instead of a string:

    ->order(new Zend_Db_Expr("name like 'C%' DESC"))->
    

    There's also an undocumented shortcut: the column-delimiting function assumes that any string containing parentheses is very likely to be an expression instead of just a column name. So the following would work too:

    ->order( "(name like 'C%' DESC)" )->