19

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));

Does anyone know what I'm doing wrong?

18

Try this.

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

If you followup the the following link, http://api.drupal.org/api/drupal/includes!database!database.inc/group/database/7 This will tell you that,

Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself.

So

SELECT nid, title FROM {node} WHERE title LIKE :title%;

Is incorrect.

The query should be

SELECT nid, title FROM {node} WHERE title LIKE :title;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.