Search code examples
phpzend-frameworkprepared-statementsql-like

How to Bind and LIKE in Zend Framework


I am trying to make a query where there is a bind and a LIKE. The query itself if I change the where for 1 works, so it is a problem of the bind and query.

Can someone give me a hand with that:

$vendor = $this->fetchAll(
            $this->select()
                ->setIntegrityCheck(false)
                ->from('vendor', array('vendor_id'))
                ->join('user', 'vendor_user_id = user_id', array('user_id','user_name'))
                ->where("user_name LIKE (':keyword%')")
                ->limit(10)
                ->bind(array(
                    'keyword' => $keyword,
                ))
        );

I am trying to get something like this for the keyword "Cake"

.
.
.
WHERE user_name LIKE ('Cake%')
LIMIT 10

Solution

  • Usually the percent % is not escaped. So you can use it inside your bind function or directly with where

    $vendor = $this->fetchAll(
                $this->select()
                    ->setIntegrityCheck(false)
                    ->from('vendor', array('vendor_id'))
                    ->join('user', 'vendor_user_id = user_id', array('user_id','user_name'))
                    ->where("user_name LIKE (':keyword')")
                    ->limit(10)
                    ->bind(array(
                        'keyword' => $keyword . '%',
                    ))
            );
    

    Or without using bind

    ->where('user_name LIKE ?', $keyword.'%');