开发者

how to use like query in drupal

How to write SQL LIKE Query in drup开发者_JAVA百科al ,

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,


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.


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.


drupal_query replace %% to % and %s to value string

so your code will be

$sql = "SELECT title FROM node WHERE type='%%%s' AND title LIKE '%%%S%%'";
$type = "type to use in query";
$title = "title to use in query";    
$result = db_result(db_query($sql, $type, $title));


OK, so you want the LIKE operator to refer to the title column. Use this query:

$sql = "SELECT title FROM node WHERE type='%s' AND title LIKE '%S%'";
$type = "type to use in query";
$title = "title to use in query";    
$result = db_result(db_query($sql, $type, $title));

This is because the LIKE operator requires a column name to be specified. Otherwise, your database doesn't have any idea what value you want to perform the comparison on. See here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜