hamid reza
hamid reza

Reputation: 45

how to change language in codeigniter

I've saved a product name in my DB with two language (En & Fr)

how can i load them differently by just changing the url

for example

localhost/mysite/en/products/

loads the "en_name" out of my table

and

localhost/mysite/fr/products/

loads the "fr_name" for me?

Upvotes: 0

Views: 448

Answers (3)

JBC
JBC

Reputation: 112

I think the simplest method may be to pass the uri segment to the where clause of the query.

https://www.codeigniter.com/user_guide/libraries/uri.html

https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=select#selecting-data

Something like:

$lang = $this-uri->segment(3);
$this->db->where('language', $lang);
$this->db->get('table');

Upvotes: 1

CMPS
CMPS

Reputation: 7769

The language library is used if you want to store the text in different languages in a file (it will be included in the page) and not in a database. So if the language text is stored in the database, you want to check the method responsible for checking the url segment to check if the url contains the en or the fr and load the corresponding language.

So the method to use is:

$this->uri->segment(n)

More info on how to use it:
https://www.codeigniter.com/user_guide/libraries/uri.html

and your condition should be something like:
Edit

if($this->uri->segment(1) == "fr"){
   $this->session->set_userdata('lang', 'fr');
}else{
   $this->session->set_userdata('lang', 'en');
}

Now you can easily check for the language selected from the model (db files) by checking the value of the lang Session

Upvotes: 1

hamid reza
hamid reza

Reputation: 45

i finally did it with this CI extension i18n and here is my code:

$lang = $this->uri->segment(1);
echo $prodct[$lang."_name"];

so now if i enter my url like this

localhost/mysite/en/products/

it will get those fields from DB which is like "en_name" , same goes for "fr" too.

Upvotes: 0

Related Questions