I’m using a table to save some text data with this structure:
CREATE TABLE IF NOT EXISTS `strings_en` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(80) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
This table keeps all english “strings” (really this is a text that sometimes is longer that 4kb). When I need a string I call mySQL like this:
SELECT `content` FROM `strings_en` WHERE `id`='42'
Now, I have “internationalized” my application so I have added other tables called “strings_es” or “strings_de” where spanish and dutch languages are used. Each id matches allways the same string in different languages.
In PHP I have a $language variable that contains the current selected language: ‘es’ for spanish, ‘en’ for english, etc. I get an string with this query:
SELECT `content` FROM `strings_$language` WHERE `id`='$string'
The problem is sometimes there is no translation for a given id (this id not exists in the table). For instance, in spanish doesn’t exists id=10 (strings_es), but it exists in english (strings_en). I use *strings_en* as default, so when a string don’t exist in the current language I search in english. Now I’m doing this through a PHP conditional:
$result = query("SELECT `content` FROM `strings_$language` WHERE `id`='$string'");
if (empty($result)) {
$result = query("SELECT `content` FROM `strings_en` WHERE `id`='$string'");
}
I would like to know how to do this in only one MySQL query.
You should use the language inside your strings table and make it part of the unique key (id+language). This way you won’t have to add new tables when you use more and more languages.
For example:
And with
you would get a string for the id in a given language or the default language.
Edit: I added a
string_idcolumn to act as the unique id.