user3170524
user3170524

Reputation: 23

php query search a string in a row

how to search a string in a row in php? I wrote this code:

$filterQuery .=' LIKE %' . $db->Quote(JString::strtolower($filter) . '%');

it works in mysql to search string with: LIKE '%stringtosearch%'

why it doesn't work in php?

Upvotes: 1

Views: 169

Answers (4)

Elin
Elin

Reputation: 6770

Note: @Andrew Eddie gives a better answer above

$filterQuery .=' LIKE ' . $db->quote('%'. JString::strtolower($filter) . '%');

Upvotes: 1

Becs Carter
Becs Carter

Reputation: 1250

Because your bracketed code adds in quotes around your string, do this instead...

$filterQuery .=" LIKE '%" . strtolower($filter) . "%'");

Remember you will need to sanitise/escape your data before querying the database

Upvotes: 0

Andrew Eddie
Andrew Eddie

Reputation: 988

As already noted, you forget the quotes around the %...% part. BUT, MySQL is not case sensitive by default so you can probably remove the JString call unless you've specifically configured your MySQL server to be case-sensitive. The alternative usage could then be simplified to:

$filterQuery .=' LIKE ' . $db->quote('%' . $filter . '%');

Note, however, that if you are using user input, SQL wildcards could result in a DOS attack (the user could include addition % and _ characters in the filter string). To prevent this, you'd use a format like:

$filterQuery .=' LIKE ' . $db->quote('%' . $db->escape($filter, true) . '%');

and that will escape the filter itself (and allow you to search for real underscores or % characters). This is how the core code handles this case as shown here:

https://github.com/joomla/joomla-cms/blob/staging/administrator/components/com_content/models/articles.php#L285

Upvotes: 7

Class
Class

Reputation: 3160

if it works like LIKE '%stringtosearch%' then add ''s before and after %'s like so

$filterQuery .= " LIKE '%" . $db->Quote(JString::strtolower($filter) . "%' ");
                       ^                                                 ^

Upvotes: 0

Related Questions