Hello friends,

I have a search query that uses a URL param.

I would like to insert this param into the query via place holder as this would be far more secure.

The way I am trying to do it is via the following:

$query->condition('a.dbl_title', '%' . ":search_term" . '%', 'LIKE', [':search_term' => $search_term]);

But this is not working and it looks like ':search_term' is just blank.

How would I go about correctly assigning ':search_term' to my variable $search_term??

Also, are there any other precautions I need to take with regards to sanatizing $search_term?

Kind regards,

Matt

Comments

slewazimuth’s picture

When a placeholder is used it should NOT be quoted. This is separate from the definition of the placeholder. Therefore, ":search_term" in the condition becomes :search_term.

DevMatt’s picture

Hi slewazimuth, thank your for your response.

When I try the following:

$query->condition('a.dbl_title', '%' . :search_term . '%', 'LIKE', [':search_term' => $search_term]);

I get 

ParseError: syntax error, unexpected ':'

Any idea what I could be doing wrong?

mmjvb’s picture

$query->condition('a.dbl_title', '%:search_term%', 'LIKE', [':search_term' => $search_term]);
DevMatt’s picture

Hi mmjvb, thank you for your response.

When I try,

$query->condition('a.dbl_title', '%:search_term%', 'LIKE', [':search_term' => $search_term]);

The place holder :search_term is still not being assigned to $search_term,

Any I idea what I could be doing wrong??

Bare in mind the condition does work when I directly add the param to the query as follows:

$query->condition('a.dbl_title', "%$search_term%", 'LIKE');
mmjvb’s picture

support this. Which means you would need to use a variable:

$likepattern = $this->t('%:searchterm%', [':searchterm' => $search_term]);
$query->condition('a.dbl_title', $likepattern, 'LIKE');
DevMatt’s picture

Hi mmjvb. Thank you, the above example you provided works perfectly. The only problem I am facing now is that using placeholders in this manner encodes the html in the variables. At the moment "&" is being stored as "&" in the database.

Is there a way to use placeholders in a way that the html is not encoded? or does the defeat the whole point of using placeholders?

Kind regards,

Matt

mmjvb’s picture

You would need to check the documentation on placeholders. Can't help you there.