To answer your question directly. You could query your current setup as follows:
-- For Dutch (pseudocode)
$query = 'SELECT var, dutch FROM translate';
$translations = array();
while loop ($row = $query) {
$translations['var'] = $row['dutch'];
}
// Then, to access translations you would:
echo $translations['titleOne'];
BUT you don't want to do this. This table structure will lead you down a path of regret. Heed our warnings. There are many ways to go about this and you've chosen to go the SQL route so here are some tips.
Change your table structure so you don't have to add a new column each time you add a new language.
Table: languages (Add a new row to support a new language)
id, locale, language
1, en_CA, English
2, en_US, English
3, en_UK, English
4, es_ES, Spanish
5, es_MX, Spanish
...
Table: translations (add a new row to add a translation)
id, locale, translation_key, translation
1, en_CA, 'hello', 'Hi from Canada'
2, en_US, 'hello', 'Hi from the US'
3, en_UK, 'hello', 'Hi from the UK'
4, es_ES, 'hello', 'Hi from Spain'
5, es_MX, 'hello', 'Hi from Mexico'
...
translations.locale
should be a foreign key pointing back to languages but I'm not sure what your SQL level is so leaving it as clear as I know how.
I assume you can figure out how to query your database from PHP. What you want to do is:
- figure out which locale to use. This will be one of the trickiest parts. Ex. should you be using the one specified in the URL, the session, the browser setting? What happens if none of those is specified? What is the fallback locale? See my
getLanguage()
function in https://stackoverflow.com/a/49758067/296555 for some ideas.
Pull all translations for that locale and store them in memory. Here is a basic query to pull all translations for a given locale.
<?pseudocode
$locale = 'en_CA';
// Find all translations for a given locale
$dbQuery = 'SELECT translation_key, translation
FROM translations
WHERE locale = :locale';
;
Put those entries you just pulled in to memory.
<?pseudocode
$translations = array();
while loop ($row = $dbQuery) {
$translations[$row['translation_key']] = $row['translation'];
}
Throughout your application, you can now access translations via that array.
echo $translations['hello'];
You'll want to do this high up in your application in a part that is called on every request. Once you have this going you will want to start optimizing. You could store the database results to the session so you don't have to query the DB on each page load or implement a more robust form of caching.
In all honesty, I think you have the right idea but the devil is in the details or so they say. Read the link that I pointed to. It isn't perfect but it should help you get to a workable solution relatively quickly.