user2519032 user2519032 - 7 months ago 51
PHP Question

PHP multilingual, $_SESSION and language switcher

I'm building a custom CMS and I'm trying to create multilingual content by using MySQL with column approach. I'm not using any framework, it's pure PHP.

Here's my code:

<?php
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
$title = $row['title'];
}
echo $title;
?>


I'm successfully printing the title from the database.

Now if I change the table posts by adding a new fields "title_en" and "title_de" and add a session

$_SESSION['current_language'] = 'en';
$_SESSION['current_language'] = 'de';


How can I create a language switcher and print the title depends what language is activated?

EDIT:

Here's the code that I'm trying

<?php
session_start();

if(isset($_GET['lang']) && in_array($_GET['lang'],['en','de'])) {
$lang = $_GET['lang'];
$_SESSION['current_language'] = $lang;

print_r($_SESSION['current_language']);
} else {
$lang = isset($_SESSION['current_language']) ? $_SESSION['current_language'] : 'en';
}
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
$title = $row['title_'.$lang];
echo $title;
}
?>


but on www.mywebsite.com/lang=de it still shows the English title.

EDIT2

I've just tried www.mywebsite.com/?lang=de and it's displaying properly. Big thanks to Павел Иванов!

Answer

Just use saved language as key. get attribute should have more priority than session saved ( for example when user want to switch language ).

if(isset($_GET['lang']) && in_array($_GET['lang'],['en','de'])) {
   $lang = $_GET['lang'];
   $_SESSION['current_language'] = $lang;
} else {
   $lang = isset($_SESSION['current_language']) ? $_SESSION['current_language'] : 'en';
}
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
    $title = $row['title_'.$lang];
    echo $title;
}

Edit: language switcher is simple ul>li list in url with lang="Your lang"