Insert array into database in a single row Insert array into database in a single row database database

Insert array into database in a single row


it's doable:

$title = serialize($array);

and then to decode:

$title = unserialize($mysql_data);

but as mentioned it really lessens the benefits of a database in the first place. i'd definitely suggest looking into a multi-table or multi-column option instead, depending on the amount of languages you want to support and if that number will change in the future.

edit: a good point mentioned by dcousineau (see comments)

Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64_encode() calls and then use base64_decode() before you unserialize.

adjusted code for those situations:

$title = base64_encode(serialize($array) );$title = unserialize(base64_decode($mysql_data) );


There's really only two reasonable choices here:

Join with another table
pros: unlimited titles in unlimited languages
cons: join overhead is more computationally expensive, SQL is marginally more complex to update/insert etc

Multiple columns
eg: TITLE_EN, TITLE_NL, TITLE_DE
pros: fast to insert, select, etc
cons: limited number of languages, adding more is an ALTER TABLE

Given our two choices, you usually should should pick the first one. Unless you're dealing with just an obscene amount of transactions that cannot be parallelized, or you absosmurfly can ensure that you will never add languages, the extra flexibility in schema layout will save you headaches in the long run.


Arrays do violate normalization; in my experience with internationalization databases I've found that having a the phrases normalized is the best design,

I allows you to easily make wholesale copies of rows - for instance 'es' to 'es-mx' or 'en' to 'en-US', 'en-GB', and my favorite: 'xx-piglatin'. In an array schema, you would either have to re-write every record or add complex parsing or use something more complex than arrays, like XML.

It is relatively easy to use LEFT JOINs for find untranslated phrases for work and also to use COALESCE to return a default so the program remains usable even if the phrase is not translated.