8.3.x database.inc db_like($string)
8.0.x database.inc db_like($string)
8.1.x database.inc db_like($string)
8.2.x database.inc db_like($string)
8.4.x database.inc db_like($string)
7.x database.inc db_like($string)

Escapes characters that work as wildcard characters in a LIKE pattern.

The wildcard characters "%" and "_" as well as backslash are prefixed with a backslash. Use this to do a search for a verbatim string without any wildcard behavior.

For example, the following does a case-insensitive query for all rows whose name starts with $prefix:

$result = db_query(
  'SELECT * FROM person WHERE name LIKE :pattern',
  array(':pattern' => db_like($prefix) . '%')

Backslash is defined as escape character for LIKE patterns in DatabaseCondition::mapConditionOperator().


$string: The string to escape.

Return value

The escaped string.

Related topics

19 calls to db_like()
comment_form_validate in modules/comment/comment.module
Validate comment form submissions.
DatabaseBasicSyntaxTestCase::testLikeBackslash in modules/simpletest/tests/database_test.test
Test LIKE query containing a backslash.
DatabaseBasicSyntaxTestCase::testLikeEscape in modules/simpletest/tests/database_test.test
Test escaping of LIKE wildcards.
DrupalDatabaseCache::clear in includes/cache.inc
Implements DrupalCacheInterface::clear().
EntityFieldQuery::addCondition in includes/entity.inc
Adds a condition to an already built SelectQuery (internal function).

... See full list


includes/database/database.inc, line 2669
Core systems for the database layer.


function db_like($string) {
  return Database::getConnection()->escapeLike($string);


Dave Reid’s picture

You have to use db_like() with a query builder (like db_select()) and not the simple db_query() function otherwise your query will not work. See http://drupal.org/node/1182428 for more details.

aendrew’s picture

Despite that issue even noting there's an invalid example on this page, it still has not yet been updated -- like, a year later. Silly.

Here's an example how to actually use it. From the Drupal 8 API page:

$result = db_select('person', 'p')
  ->condition('name', db_like($prefix) . '%', 'LIKE')
gkgaurav10’s picture

as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call escapeLike() on it. For example, $injected_database->escapeLike($string);

SlashCrew’s picture

an example

  $search_string ="per";
  $result = db_query('SELECT title
                      FROM {node} n
                      WHERE n.title like :title'
                      ,array(':title' => "%".$search_string."%"))
tenken’s picture

This example is wrong, if simply because you're not escaping/checking $search_string.