欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

drupal 7 db_query like % 查询 百分号 自己亲自做的 有大用 有大大用

db_like    本身是不区分大小写的  ignorecase ignore case



I have a query like this in Drupal 6:
$sql
= 'SELECT sid, score FROM search_index WHERE word LIKE "%%%s%%"'; $result = db_query($sql,$search_term);

And it worked fine, but now I'm upgrading to Drupal 7.

I read up and this is supposed to work, but it's not:

$sql = 'SELECT sid, score FROM search_index WHERE word LIKE "%:term"';
$result = db_query($sql,array(':term'=>$search_term));


D7 中 正确答案:
$sql = 'SELECT sid, score FROM {search_index} WHERE word LIKE :term'; $result = db_query($sql, array(':term' => '%' . db_like($search_term)));

是的,Drupal的7引入了一个新的DB API,如db_select()db_insert()db_update()db_condition()db_like(),等代替使用db_query(),但建议使用db_select()

https://api.drupal.org/api/drupal/includes!database!database.inc/group/database/7.x

https://www.drupal.org/docs/7/api/database-api/database-api-overview


请注意,占位符应为“完整”值。例如,当运行 LIKE 查询时,SQL 通配符 % 应该是值的一部分,而不是查询本身。

所以

SELECT nid, title FROM {node} WHERE title LIKE :title%;  //是不正确的

SELECT nid, title FROM {node} WHERE title LIKE :title;   //是正确的



d7 中 正确的方法

$gh = db_query(
      "select u.name as gh from users u
inner join field_data_field_diqu d on u.uid=d.entity_id
where mail like :mail
and d.entity_type='user' and d.bundle='user'
  and d.field_diqu_value=:diqu   ",
      array(':mail' => '%' . db_like($email) . '%', ':diqu' => $diqu)
  )->fetchField();
  if (empty($gh)) {
      drupal_set_message('未查到此人的 AD 信息!,此邮箱为: ' . $email);
  }


普通分类: