如何在drupal中编写SQL LIKE查询,
SELECT title FROM { node } WHERE type='%s'
我想添加LIKE CONDITION IN THAT
SELECT title FROM { node } WHERE type='%s' AND LIKE '%S%'
我认为我写错了像查询formnat,可以重写并告诉我,
答案 0 :(得分:12)
只需使用%即可逃脱。
$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
}
节点类型不需要转义。
答案 1 :(得分:4)
drupal_query将%%替换为%,将%s替换为值字符串
所以你的代码将是
$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));
答案 2 :(得分:3)
好的,您希望LIKE
运算符引用title
列。使用此查询:
$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));
这是因为LIKE
运算符需要指定列名。否则,您的数据库不知道您要执行比较的值。请参阅here。
答案 3 :(得分:3)
以下是如何在动态查询中使用LIKE的示例( 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()
用于转义在LIKE模式中用作通配符的字符。