Jo Ey
Jo Ey

Reputation: 11

PHP: Select a value from an imploded array in MySQL

I have a tag system where the tags are stored inside a row as an imploded array like so: "value1, value2, value3, etc..."
And I'm trying to make a tag search page but I have no idea how to convert it to an array to see if the certain tag someone searched in is in the array(because I can't explode it whilst using SELECT).

Can anyone help or is it impossible?

Thank you all for your help, it worked.

Upvotes: 1

Views: 1790

Answers (5)

William Entriken
William Entriken

Reputation: 39293

Normalize your database with

tags {
  object_id
  tag_id
}

Or, if you're lazy, just do

UPDATE tags = CONCAT(",", tags, ",") FROM table

And then

SELECT * FROM table WHERE tags LIKE '%,selected_tag,%'

Upvotes: 0

Ivan Fateev
Ivan Fateev

Reputation: 1061

I think the better way is to normalize data and move tags to a separate table and then join tags to your entity. Search would be fast and easy =)

Upvotes: 1

WojtekT
WojtekT

Reputation: 4775

There's a mysql function called FIND_IN_SET which operates on comma separated strings. For example:

SELECT * FROM posts WHERE FIND_IN_SET('some_tag', post_tags)>0

Documentation here: Mysql FIND_IN_SET

Upvotes: 3

Anas
Anas

Reputation: 5727

You can just use "LIKE" in your select query

SELECT row FROM table WHERE tag LIKE '%search_value%'

Upvotes: 0

DaneSoul
DaneSoul

Reputation: 4511

Read $tags_str from your data base.

Convert string to array:

   <?php
    $tags_str = "value1, value2, value3";
    $tags_arr = explode(', ', $tags_str);
    ?>

Then use in_array() PHP function for searching mathes.

Upvotes: 0

Related Questions