| 7 database.inc | db_like($string) |
| 8 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().
Parameters
$string: The string to escape.
Return value
The escaped string.
Related topics
18 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).
File
- includes/
database/ database.inc, line 2610 - Core systems for the database layer.
Code
function db_like($string) {
return Database::getConnection()->escapeLike($string);
}
Comments
Cannot be used with db_query() or db_query_range()
PermalinkYou 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.
Misleading example
PermalinkDespite 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')->fields('p')
->condition('name', db_like($prefix) . '%', 'LIKE')
->execute()
->fetchAll();
db_query and the like operator
Permalinkan example
<?php
$search_string ="per";
$result = db_query('SELECT title
FROM {node} n
WHERE n.title like :title'
,array(':title' => "%".$search_string."%"))
->fetchAll();
print_r($result);
?>