PHP multilingual, $_SESSION and language switcher - php

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 Павел Иванов!

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"

Related

This script is too slow, any way to improve its performance?

This script is too slow, any way to improve its performance? The word is loaded by returning this function within the page, and fetching a table in the database.
The connection is via PDO and the MySQL database
function fnc_translate($texto) {
include("conn.php");
$lang['pt-br'] = 'PT_BR';
$lang['en'] = 'EN';
$lang['es'] = 'ES';
$lang['no'] = 'NO';
if(!isset($_GET['lang']) && !isset($_SESSION['lang'])){
$stmt = "SELECT LANG_PT_BR FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_PT_BR";
$_SESSION['lang'] = 'pt-br';
}elseif(!isset($_GET['lang']) && isset($_SESSION['lang'])){
$stmt = "SELECT LANG_".$lang[$_SESSION['lang']]." FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_".$lang[$_SESSION['lang']];
}elseif(isset($_GET['lang'])){
$stmt = "SELECT LANG_".$lang[$_GET['lang']]." FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_".$lang[$_GET['lang']];
$_SESSION['lang'] = $_GET['lang'];
}else{
$stmt = "SELECT LANG_PT_BR FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_PT_BR";
$lang = $_SESSION['lang'] = 'pt-br';
}
try {
$sql=$conn->prepare($stmt);
$sql->bindParam(':texto',$texto,PDO::PARAM_STR);
$sql->execute();
$row=$sql->fetch();
} catch (PDOException $e) {
return $texto = $texto;
}
if(isset($row[$row_name])){
return $texto = $row[$row_name];
}else{
return $texto = null;
}
}
My problem is solved! As you already imagined, the problem was not in the code above, but in the settings in the PHP.INI of the local server. I used the Cloud settings and the speed was normalized.

Setting a dynamic page title with php not working?

I am trying to set a dynamic page title for my one of my pages but it seems to not be working. I use phpMyAdmin and I have the same code that is dynamic for another page that grabs a server name. I cannot figure out what I am doing wrong.
Here is my my current code: URL looks like this http://test.com/index.php?category=test
switch ($pageTitle) {
case 'index.php':
if(isset($_GET['id']) && !empty($_GET['id'])){
$id = (INT)$_GET['id'];
$query = $database->query("SELECT `name` FROM `categories` WHERE `category_id` = '$id'");
$fetch = $query->fetch_assoc();
$pageTitle = $fetch['name'];
} else {
$pageTitle = "test title";
$description = "test desc";
}
break;
Here is another code snippet that works and uses a server name: URL looks like this http://test.com/server.php?id=#
case 'server.php':
if(isset($_GET['id']) && !empty($_GET['id'])){
$id = (INT)$_GET['id'];
$query = $database->query("SELECT `name` FROM `servers` WHERE `id` = '$id'");
$fetch = $query->fetch_assoc();
$pageTitle = $fetch['name'];
} else {
$pageTitle = "Server Details";
}
break;
Anyone know why I cannot get the name of the category?

Redirect based on URL parameter and if URL parameter is available in table row - PHP MySQL

I have a table where one of the attribute is version.
The table name is versions.
I want to redirect users to a default page if the URL parameter also called version is NULL or not present, and if the version value is not in my table.
So far I've this. It does not work.
$stonevar = isset($_GET['version']) ? $_GET['version'] : NULL;
if (empty($stonevar)) {
header("Location: index.php?version=default");
}
$id = $_GET['version'];
$result = $db->query("SELECT * FROM `versions` WHERE version='$id'");
while ($row = $result->fetch_assoc()) {
$varex = $row['version'];
}
if ($varex == NULL) {
header("Location: index.php?default");
}
You have to add exit(); after header function.
Try Something like:
<?php
$stonevar = isset($_GET['version']) ? $_GET['version'] : NULL;
if (empty($stonevar)) {
header("Location: index.php?version=default");
exit();
}
$result = $db->query("SELECT * FROM `versions` WHERE version='$stonevar'");
while ($row = $result->fetch_assoc()) {
header("Location: index.php?".$row['version']);
exit();
/*
* or something you want to do if version exist
*/
}
header("Location: index.php?default");
exit();
?>
Use $result->num_rows to count the result and see if the version exists.
$stonevar = isset($_GET['version']) ? $_GET['version'] : NULL;
if (empty($stonevar)) {
header("Location: index.php?version=default");
}
$id = $_GET['version'];
$result = $db->query("SELECT * FROM `versions` WHERE version='$id'");
$total_num_rows = $result->num_rows;
if ($total_num_rows>0) {
while ($row = $result->fetch_assoc()) {
$varex = $row['version'];
}
}
else{
header("Location: index.php?default");
}

PHP & MySQL do action for each row in database

I am building a site, and essentially what this PHP algorithm will do is look at a product (row in MySQL database) one at a time, and do a process accordingly.
I put a lot of research into this but couldn't find anything, any help would be greatly appreciated!
My Code (currently returning nothing for echo variables):
<?php
include_once 'dbconnect.php';
$query = "SELECT * FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$pro_code = mysql_result(mysql_fetch_array(mysql_query('SELECT product_code FROM track')));
$currency = mysql_fetch_array(mysql_query('SELECT currency FROM track'));
$cc = mysql_fetch_array(mysql_query('SELECT cctld FROM track'));
$initial_price = mysql_fetch_array(mysql_query('SELECT initial_price FROM track'));
$url = 'test';
}
echo $pro_code;
echo $currency;
echo $initial_price;
?>
First of all, try the advice about PDO and stuff from Jay Blanchard some day.
Secondly I've tried to answer your question anyway and I've tried to interpret your complete intention. I put comments in the code:
<?php
include_once 'dbconnect.php';
$query = "SELECT * FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
//You need to read the row variable as an array
$pro_code = $row['product_code'];
$currency = $row['currency'];
$cc = $row['cctld'];
$initial_price = $row['initial_price'];
//$url is not used.. I asume a test to get the external source ;-)
$url = 'test';
if ($url == $cc) {
//if you want to print every row, you must echo inside the while loop
echo $pro_code;
echo $currency;
echo $initial_price;
} elseif ($url == 'test') {
//do something else here
} else {
//do something for all the other cases here
}//end if
}//end while
?>
Why do you query the same table multiple times, your code should be written like this:
include_once 'dbconnect.php';
$query = "SELECT product_code, currency, cctld, initial_price FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo $row['product_code'];
echo $row['currency'];
echo $row['cctld'];
echo $row['initial_price'];
}
and please upgrade to mysqli or PDO

php/MySQL Query Loop only using first value

I'm writing an online shop, and I've come across an issue with a function which I'm hoping someone can help me with. The function is designed to determine if the product exists in alternate formats and link to those from the sidebar. For example, a product may exist in DVD, Blu-Ray and Digital Download.
This is my function code:
function formatExists($format, $pid) {
global $conn; global $dbname; global $loginid;
mysql_select_db($dbname, $conn);
// Get author and description of the requested product
$query = "SELECT description, author FROM products WHERE productid = $pid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$author = $row['author'];
$description = $row['description'];
}
// Find other products with the same description & author in requested format
$query = "SELECT productid FROM products WHERE format = $format AND description = '$description' AND author = '$author'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$rpid = $row['productid'];
}
if($rpid) {
return $rpid;
} else {
return 0;
}
}
I've written a loop in another part of the code, which gets all of the formats from the database, then runs the above function on them to try to find out which formats the product is available in:
$query = "SELECT formatid, description, postage FROM formats";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$id = $row['formatid'];
$desc = $row['description'];
$post = $row['postage'];
... STUFF ...
}
When '... STUFF ...' was '$bodycontent .= $id';" it echoed every format ID in the database, this is the behavior I expected. However, when I changed it to:
$pid = formatExists($id, $productid);
if($pid) {
$query = "SELECT price FROM products WHERE productid = $pid";
$result = mysql_query($query);
$pricedata = mysql_fetch_array($result, MYSQL_ASSOC);
$pprice = $pricedata['price'];
$bodycontent .= "<span>";
if($pid != $productid) {
$bodycontent .= "<a href='$siteroot/index.php?page=product&id=$pid'>";
}
$bodycontent .= "$desc - &dollar;$pprice";
if($postage) {
$bodycontent .= " + P&P";
}
if($pid != $productid) {
$bodycontent .= "</a>";
}
$bodycontent .= "</span>";
}
It stopped operating in the desired fashion, and just started returning the response for the first format ID.
If I manually change 'formatExists($id, $productid)' to 'formatExists(2, $productid)' then the price and link update, so the function is working correctly. For some reason, however, it's not running once for each category, it's just running once in my loop.
Any help will be much appreciated.
the function you are using is wrong !!! i mean -> mysql_fetch_array
you should change mysql_fetch_array with mysql_fetch_assoc
to see the true result.

Categories