As mentioned you can implode/explode it.
Generally speaking saving data this way renders it almost impossible to search on. It's usually better to save it in a separate table as it's essentially a Many To One relationship. That is up to you to decide, but I wouldn't do it just to "cut corners" as things like counting and grouping will suffer because indexing such a field offers much less performance benefit then a separate table.
That said, one suggestion I have is to add the deleimters to the front and back like this:
,1,2,12,13,145,
Why you ask. Because consider this query
SELECT * FROM table WHERE field LIKE '%1%'
Now if that list is field
it will match any row that has a 1
anywhere. This is probably not what you want. Such as matching 23,215,54
. So the simple solution is to add the delimiters to the front and back and the query as well like this.
SELECT * FROM table WHERE field LIKE '%,1,%'
Now we are only matching fields with ,1,
, because we can include the delimiters in the search. It should be pretty obvious that ,1,
is not the same as 215
.
You have to think hard how you will use this data as you will be limited to searching and grouping using only queries that use Like %data%
to match with.
You can simply add them by doing this:
$var = ','.implode(',', $arr).',';
The good thing is there are easy ways to remove these extra delimiters, if you choose to use them:
$var = trim($var,',');
//then we would explode it
$arr = explode(',', $var);
You can even do it right in the SQL with
SELECT TRIM(BOTH ',' FROM field ) AS trimmed;
I would be vary careful in your choice of delimiters, if it's possible to have a ,
in the data at all chose something like |
and make sure to strip the delimiter from input data otherwise you may never be able to separate the data properly in the future.
I typically use this method when I use tree data with a Materialized Path schema, but that's a story for another time...