I want to search if a user submitted comment contains comma separated bad words in the database.
Table bad_word
:
id | words |
---|---|
1 | foo bar, fooBar |
2 | aaa bbb, ccc ddd |
I’m using the following code but it only work for one bad word per row on database:
$comment = request('comment');
$bad_word_exists = AppBadWord::whereRaw("LOCATE(words, ?) > 0", [$comment])->exists();
Expected output:
$comment | $bad_word_exists |
---|---|
foo | false |
foo bar 123 | true |
Thanks
2
Answers
First we convert the comma separated data into rows using
CROSS JOIN JSON_TABLE()
then we search usingLOCATE()
functionDemo here
As stated by apokryfos, it would be better to normalise the values in your
words
column.If your client wants to add multiple words as a comma separated list, you can still enter them into your table as separate words: