Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use like query in drupal

How to write SQL LIKE Query in drupal ,

SELECT title FROM { node } WHERE type='%s'

i want to add the LIKE CONDITION IN THAT

SELECT title FROM { node } WHERE type='%s' AND LIKE '%S%'

i think i writtern wrong like query formnat, can rewrite and tell me,

like image 624
Bharanikumar Avatar asked Nov 02 '10 16:11

Bharanikumar


2 Answers

Just use % to escape.

$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');

while ($row = db_fetch_object($result)) {
     // do stuff with the data
}

Node type does not need escaping.

like image 95
Kevin Avatar answered Oct 21 '22 02:10

Kevin


And here is an example with how to use LIKE in a dynamic query (Drupal 7 Only):

$query = db_select('node', 'n')
        ->fields('n', array('title'))
        ->condition('type', 'my_type')
        ->condition('title', '%' . db_like(search_string) . '%', 'LIKE');
    $result = $query->execute()->fetchCol();

db_like() is used to escapes characters that work as wildcard characters in a LIKE pattern.

like image 29
Felix Eve Avatar answered Oct 21 '22 02:10

Felix Eve