I have a comma separated list of numbers in a MySQL entry ‘id_user’ like so:
127,130,150,12,4,7,8,9
What is the best way to find a number in this comma-separated list and (1) remove it with the comma if it’s with other numbers or (2) just remove itself if the number is by itself like:
127
Then update the MySQL entry.
So if I wanted to remove 150 from the list, it would be updated in the MySQL as:
127,130,12,4,7,8,9
I want to avoid trying to remove the id ’12’ but end up removing the ’12’s in numbers like 127 or 512
Thank you!
Reading between the lines, it sounds to me like you are storing a list of foreign keys in a comma-separated string field to represent a many-to-many relationship. This is not a good idea.
What you should do instead is create a table to store the relations.
For example, lets say you have a table called
usersand you want to store friend relationships between them. What you are doing is something like this (N.B. I realised this is actually not a great example as I wrote the end but I’m sticking with it for now):Whereas what it’s much better to do is something like this:
usersfriendsTo select Dave’s friends you can do
…and to delete the relationship between Dave and Bob (what you want to do here), you can simply do