I\'m building a multi-language online site with Codeigniter. My question is how to pass data from database to the Codeigniter language files. My logic so f
You are on the right track. You’ll want to create a language file on the fly (e.g. whenever you update the language contents of your database)
1st: the database layout
Create a table lang_token
with columns id
, category
, description
, lang
, token
and populate its fields like this:
CREATE TABLE IF NOT EXISTS `lang_token` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category` text NOT NULL,
`description` text NOT NULL,
`lang` text NOT NULL,
`token` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `lang_token` (`id`, `category`, `description`, `lang`, `token`)
VALUES
(1, 'error', 'noMail', 'english', 'You must submit a valid email address'),
(2, 'error', 'noUser', 'english', 'You must submit a username');
2nd: About CodeIgniter language files
CodeIgniter will look first in your application/language directory, Each language should be stored in its own folder. Make sure you have your English or German, etc. subdirectories created e.g. application/language/english
3rd: Controller function to create language file on the fly
About The Codeigniter language files:
It's a good practice to use a common prefix (category) for all messages in a given file to avoid collisions with similarly named items in other files
There structure is like: $lang['category_description'] = “token”;
function updatelangfile($my_lang){
$this->db->where('lang',$my_lang);
$query=$this->db->get('lang_token');
$lang=array();
$langstr="<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
*
* Created: 2014-05-31 by Vickel
*
* Description: ".$my_lang." language file for general views
*
*/"."\n\n\n";
foreach ($query->result() as $row){
//$lang['error_csrf'] = 'This form post did not pass our security checks.';
$langstr.= "\$lang['".$row->category."_".$row->description."'] = \"$row->token\";"."\n";
}
write_file('./application/language/'.$my_lang.'/general_lang.php', $langstr);
}
Final notes:
updatelangfile(‘english’)
Don’t forget to load the file helper and language class in the constructor of the controller where updatelangfile() is located:
function __construct(){
parent::__construct();
$this->load->helper('file');
$this->lang->load('general', 'english');
}