Press ESC to close

Manoj Bist

MYSQL FIND_IN_SET Multiple Value

 MYSQL FIND_IN_SET Multiple Value

Syntax

FIND_IN_SET(pattern, strlist)
FIND_IN_SET('wings', 'tacos,wings,roast,etc')

FIND_IN_SET returns the index position of the search string if matched otherwise returns 0 or NULL if the field is an empty or empty string like “”.

FIND_IN_SET only accepts one value to be searched against the comma-separated list of strings in the MySQL table column.

Above is the description from MySQL & MariaDB.
but sometimes there is the time when we need to search with multiple strings using the FIND_IN_SET function.
Actually, I was suffering from the same thing and i searched lot in google and nothing helped me. I was working in Laravel Project and nothing was there to help me.
Later I got a trick to sort it out.
Here I’m sharing the same trick, might help someone else.

What I did is, broken down the search strings and made an array with it and then loop through those and make a where condition. Like this:

if you are in Laravel

$searchString = $request->search_input;

//you can also perform a check here if the string contains comma or space then explode according to that

$parts = explode(‘ , ‘,   $searchString );

$query = DB::table(‘post’);

$query->where( ‘post_title’ ,  $request->post_title);
if( !empty( $parts ) ) {

    for( $i=0; $i<=count($parts)-1; $i++ ) {
        $query->orWhereRaw( “find_in_set(‘{$parts[$i]}’ , tags)” );
    }
}
$results = $query->get();
dd($results);

 

In the above query, tags is my table column in the post table.

Yeah I know, looping a query is a bad thing, but here we not doing anything bad by looping the where condition, before calling $query->get(), we can do whatever we want with queries because its only in our controller not in MySQL. But its important to perform checks on your inputs before passing them to queries. Like you can check if a string contains a comma, or space or after exploding you can check if anything empty going to the database query. That’s all in your hand. Get your hands dirty you will know the things clearly.

You can use the above trick not only in Laravel but everywhere. Always does the trick and it actually saved me.

Correct me if I’m wrong.

We never know everything.

Manoj Bist

A Passionate Web Developer/Designer With over 6 years of experience in the industry, Manoj Bist is a seasoned professional who combines technical expertise with a down-to-earth demeanor. As a lover of both technology and design, he thrives on creating seamless digital experiences that captivate and inspire.

Leave a Reply

Your email address will not be published. Required fields are marked *