Storing Multiple Items In One MySQL Field – Alternate Method
On 11.02.2008 by Paul Robinson |
A little while ago I posted about storing more than one piece of information in a MySQL table field. This can come in handy for quite a few reasons, none of which I can think of right now, but really it does. Anyway here is a trick for doing this in a much better way, [...]
A little while ago I posted about storing more than one piece of information in a MySQL table field. This can come in handy for quite a few reasons, none of which I can think of right now, but really it does.
Anyway here is a trick for doing this in a much better way, in my opinion. First put the information you want to store into an array, so let’s for an example take URL’s & Their alt text.
$info = array('http://wordpress.org' => 'A excellent blogging platform',
'http://celeborama.net' => 'A excellent celebrity photo site');
I think you get the idea. So normally storing this info in a database would require two fields & probably a table to it’s self. However you could store this in a single field by using serialize(), this compacts the array into a byte string so that you can store it in a single field. All you need to do when it is retrieved from the database is use unserialize() and it will be turned back into a fully working array. Here is a quick example:
$info = array(...) //the elipsis represents the information written above.
$serial_info = serialize($info);
// Now we store the info inside $serial_info into a database...
// Ok. Now we have retrieved the information from the db field 'links' into a var named $row
$info = unserialize($row['links']);
That would give you back an array, like the one you started with, inside the variable $info. Just remember that when you serialize an array or object the resulting byte string can be rather large so you will probably need to store it in a text field and not in a varchar field.
Well I hope that has helped you. Again it may not seem like something you’d want to do, but believe me when you want to do it you’ll thank god, and me hopefully, that you now know how.
Also a huge thank you to the person who donated a nice present to the hosting fund. Thank you.
Leave a comment