Storing Multiple Values In A MySQL Database
So after a little rest from coding I’m back with this little conundrum that hit me about 4 or 5 year ago, but seems to [...]
So after a little rest from coding I’m back with this little conundrum that hit me about 4 or 5 year ago, but seems to have come back to haunt a lot of people recently.
The problem is storing multiple values in one field when using a MySQL database. The project I worked on all that time ago was a music database and one of the fields held the members of the band. I could have created a secondary table to hold members and used a single to many relationship but personally I feel it would be inefficient since it’s very rear to have the same band member in two different bands. It does happen, but not often enough to warrant another table.
So how do I carry all that information in one database field? I hear you cry. Well I found the best way is to place some sort of seperator in the database field. Preferably a character you probably won’t use. So my members field looked a little like this:
Cheryl Cole^ Sarah Harding^ Nicola Roberts^ Nadine Coyle^ Kimberley Walsh
I used the carrat since I was never likely to use it in this field. Now when you retreive the information from the database you use a small PHP function to seperate each member from the database. Here is the function I wrote:
function seperateMembers($members)
{
if(strpos($members, '^') === FALSE)
{
return '<ul><li>'.$members.'</li></ul>';
}
else
{
$memberArray = split('^', $members);
$o = '<ul>';
foreach($memberArray as $member) {
$o .= '<li>' . $member . '</li>';
}
$o .= '</ul>';
return $o;
}
}
This makes a standard X/HTML unordered list with each item in. So it will end up looking something like this:
- Cheryl Cole
- Sarah Harding
- Nicola Roberts
- Nadine Coyle
- Kimberly Walsh
The PHP function is pretty much self explanatory but here is a quick run through.
We first check to see if there are any carrats by using strpos which returns false if it can’t find one. In this case we assume there is only one member and return that single member in a unordered list.
If there is a carrat we use split() which accepts a regex pattern for splitting. Since the carrat(^) has a special meaning in regex we backslash it so that PHP will interpret it literally. Then we use a simple foreach loop to go through each item in the array we created using the split, and place them into a unordered list. Finally we return that list. Throughout the last part I concatenate to a variable and return that. I find this is the best way, but there are probably other ways to do that.
So there you go. That’s a simple way of storing multiple values in a single MySQL table field. If you have any questions or you have anything to add please feel free to comment.







Discussion: 11 Comments
Nice, been looking for somthing like this…but…how do you echo the list in a page?
echo $members?
Thanks in advance for your reply.
Hey, I included
at the bottom and it showed. The only problem is that is showing an extra empty item. With this I mean a bullet followed by nothing. Any ideas? I know this is an old post, but the only I found on this issue so far.
Hi Gus.
Yep this is a really old post. In fact there is a completely different way to do this now. I’d forgotten all about it so thanks for reminding me.
The best way to store multiple items in a database field is the way most large web applications do these days and that is a serialized array. Basically you take your data, let’s use the data from the post as an example, and serialize it.
//Place data in an Array $data = array('Cheryl Cole', 'Sarah Harding', 'Nicola Roberts', 'Nadine Coyle', 'Kimberley Walsh'); //Serialize the array $data = serialize($data); //Code to store in database would followA serialized array is simply a string representation of the data you stored in the array. To get your data back simply retrieve it as you would normally from the database & the run unserialize on it.
The great thing is that the data is an array again & PHP will treat it as such. Things like
print_randarray_popwill all work just as they would on an array created through normal methods.I hope that helps. Let me know if you have any questions about the whole serialization process.
Thanks for reply. LOL. I started working on this (and made it work) before I realized that, yeah, the post was two years old. Which is not that much really, and it is the easiest way to do it anyway for a total newbie like me.
I really appreciate your reply because I have no idea what you’re talking about
My problem is conceptual, I just don’t understand the serialize approach in full. In my website (I think I went too far with this, by the way), I have an artist table in which I store band members and genres in two different columns. I’m gonna try right now to serialize a list of genres and members sent from a form and to unserialize it. This way I can see the mechanics of it and understand the challenges. I’ll come back here with the results. Again, I appreciate your help.
I’m going to start writing new tutorials again tomorrow, so if you like I’ll make an updated version of this post explaining how serialization works. I’ll try to explain the concept & give examples of how to whole process works if that will help.
That sounds fun…let me get down to this and see where I get before I start asking questions. My implementation problems might be helpful to your tutorial as you can address practical issues civilians like myself face when playing with fire (php-mysql fire).
No problem. I’ll start writing up the draft tomorrow, just fire any questions etc you have and I’ll add the solutions into the post as I go.
Hey Paul, started playing with serialize with mixed results.
First the bad.
http://lobotoradio.com/artistinfo.php?id=5
As you can see there the results of the genres column for an artist comes out as Array, which means (according to my limited knowledge) that I’m not unserializing. However, I am unseriliazing.
Here’s what I used to serialize.
1. Named the multiple select form genres[]
2. The action page includes
and
$insert = mysql_query("insert into artists values ('$serializedgenres')"These changes fill the genres column in my database with things like
a:3:{i:0;s:4:"Rock";i:1;s:10:"Electronic";i:2;s:6:"Reggae";}But when I try to unserialize in the artist page:
All I get is array.
What am I doing wrong? Will save a shower of questions for later on
If you want to see the contents before you do anything with it you will need to use
print_r()orvar_dump()instead of echo. Just remember that unlike echo you must use brackets, you cannot omit them as you can with echo.Hope that helps.
Question: how would someone use an sql statement to grab or look for just one of the members? Say I need to NOT show the name ‘Sarah Harding’ in a php while statement. how would the sql statement look?
$sql = “SELECT members FROM members WHERE name NOT IN (the_array)”;
that’s what I have, and it works if there is only one entry, as soon as it has a bunch of seperated values, it stops working.
Hi David,
this is quite an old post and while sometimes still useful I would strongly advise using serialization to store multiple values in a single field.
To answer your question though, I have never found a way to solve that problem. The only thing I can think of is to use
NOT LIKEwith wildcards or maybe use the MySQL regex command. I’m not super familiar with MySQL though so how the regex command would work is anyone’s guess.