How can I create a dynamic menu created in a database?
A sample of the menu table :
ID NAME URL IDPARENT
----------------------------------
1 Accueil #Accueil 0
2 Parcs #Parcs 0
3 Allemagne #Allemagne 2
4 Berlin #Berlin 3
5 France #France 2
6 Contact #Contact 0
The result should be :
<ul>
<li>Accueil</li>
<li>Parcs</li>
<ul>
<li>Allemagne</li>
<ul>
<li>Berlin</li>
</ul>
<li>France</li>
</ul>
<li>Contact</li>
</ul>
SOLVED : My code :
<?php
//connection to the database
$dbhandle = mssql_connect('*****', '*****', '*****')
or die("Couldn't connect to Server");
//select a database to work with
$selected = mssql_select_db("*****", $dbhandle)
or die("Couldn't open database");
//declare the SQL statement that will query the database
$query = "SELECT * FROM CATEGORIES ";
//execute the SQL query and return records
$result = mssql_query($query);
//display the results
while($row = mssql_fetch_array($result))
{
// Assign by reference
$thisref = &$refs[ $row['ID'] ];
// add the the menu parent
$thisref['IDCategoriePere'] = $row['IDCategoriePere'];
$thisref['NOM'] = $row['NOM'];
$thisref['URL'] = $row['URL'];
// if there is no parent id
if ($row['IDCategoriePere'] == 0)
{
$list[ $row['ID'] ] = &$thisref;
}
else
{
$refs[ $row['IDCategoriePere'] ]['children'][ $row['ID'] ] = &$thisref;
}
}
function create_menu( $arr )
{
$html = "\n<ul>\n";
foreach ($arr as $key=>$val)
{
$html .= '<li>'.$val['NOM']."</li>\n";
if (array_key_exists('children', $val))
{
$html .= create_menu($val['children']);
}
}
$html .= "</ul>\n";
return $html;
}
echo create_menu( $list );
//close the connection
mssql_close($dbhandle);
?>
It works fine ! but when i tried to put css (http://cssmenumaker.com/menu/flat-jquery-responsive-menu), the dropdown doesn't show :(
Result with and witout css :
<style>
/* CSS Document */
#import url(http://fonts.googleapis.com/css?family=Open+Sans);
#import url(http://fonts.googleapis.com/css?family=Bree+Serif);
#container {
margin: 0 auto;
}
nav {
margin: 50px 0;
background-color: #E64A19;
}
nav ul {
padding: 0;
margin: 0;
list-style: none;
position: relative;
}
nav ul li {
display:inline-block;
background-color: #E64A19;
}
nav a {
display:block;
padding:0 10px;
color:#FFF;
font-size:20px;
line-height: 60px;
text-decoration:none;
}
nav a:hover {
background-color: #000000;
}
/* Hide Dropdowns by Default */
nav ul ul {
display: none;
position: absolute;
top: 60px; /* the height of the main nav */
}
/* Display Dropdowns on Hover */
nav ul li:hover > ul {
display:inherit;
}
/* Fisrt Tier Dropdown */
nav ul ul li {
width:170px;
float:none;
display:list-item;
position: relative;
}
/* Second, Third and more Tiers */
nav ul ul ul li {
position: relative;
top:-60px;
left:170px;
}
/* Change this in order to change the Dropdown symbol */
li > a:after { content: ' +'; }
li > a:only-child:after { content: ''; }
</style>
<!-- WITH PHP -->
<div id="container">
<nav>
<?php
//connection to the database
$dbhandle = mssql_connect('*****', '*****', '*****')
or die("Couldn't connect to Server");
//select a database to work with
$selected = mssql_select_db("*****", $dbhandle)
or die("Couldn't open database");
//declare the SQL statement that will query the database
$query = "SELECT * FROM CATEGORIES ";
//execute the SQL query and return records
$result = mssql_query($query);
//display the results
while($row = mssql_fetch_array($result))
{
// Assign by reference
$thisref = &$refs[ $row['ID'] ];
// add the the menu parent
$thisref['IDCategoriePere'] = $row['IDCategoriePere'];
$thisref['NOM'] = $row['NOM'];
$thisref['URL'] = $row['URL'];
// if there is no parent id
if ($row['IDCategoriePere'] == 0)
{
$list[ $row['ID'] ] = &$thisref;
}
else
{
$refs[ $row['IDCategoriePere'] ]['children'][ $row['ID'] ] = &$thisref;
}
}
function create_menu( $arr )
{
$html = "\n<ul>\n";
foreach ($arr as $key=>$val)
{
$html .= '<li>'.$val['NOM']."</li>\n";
if (array_key_exists('children', $val))
{
$html .= create_menu($val['children']);
}
}
$html .= "</ul>\n";
return $html;
}
echo create_menu( $list );
//close the connection
mssql_close($dbhandle);
?>
</nav>
</div>
<!-- WITHOUT PHP -->
<div id="container">
<nav>
<ul>
<li>ACCUEIL</li>
<li>PARCS
<!-- First Tier Drop Down -->
<ul>
<li>ALLEMAGNE
<!-- Second Tier Drop Down -->
<ul>
<li>BERLIN</li>
</ul>
</li>
<li>FRANCE
</li>
</ul>
</li>
<li>CONTACT</li>
</ul>
</nav>
</div>
Please give for a detailed answer all informations like your database type and also the query or all of your code. Also the column name NAME is a reserved SQL Keyword, so normally it is not a good idea but mssql is mostly not ANSI, so it is maybe not interesting :)
If you want a multidimensional menu, then you cannot only print out the table. You have first to order the data (pass all childs to parent) and then you can create your menu. For that you are using normally with recursive functions or methods like here the create_menu function.
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
// connect to sql server
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
// create an array to hold the references
$refs = array();
// create and array to hold the list
$list = array();
$tsql = "SELECT ID, IDPARENT, NAME, URL FROM menu_items ORDER BY NAME;"
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
// Assign by reference
$thisref = &$refs[ $row['ID'] ];
// add the the menu parent
$thisref['IDPARENT'] = $row['IDPARENT'];
$thisref['NAME'] = $row['NAME'];
$thisref['URL'] = $row['URL'];
// if there is no parent id
if ($row['IDPARENT'] == 0)
{
$list[ $row['ID'] ] = &$thisref;
}
else
{
$refs[ $row['IDPARENT'] ]['children'][ $row['ID'] ] = &$thisref;
}
}
mssql_close($conn);
/**
*
* Create a HTML menu from an array
*
* #param array $arr
* #param string $list_type
* #return string
*
*/
function create_menu( $arr )
{
$html = "\n<ul>\n";
foreach ($arr as $key=>$val)
{
$html .= '<li>'.$val['NAME']."";
if (array_key_exists('children', $val))
{
$html .= create_menu($val['children']);
}
$html .= "</li>\n";
}
$html .= "</ul>\n";
return $html;
}
echo create_menu( $list );
?>
Related
<?php
try
{
$db = new PDO("sqlite:/var/www/html/mobile_app.db");
print "<table border=1>";
print "<tr><td>Game ID</td><td>Game Name</td><td>Approved Version</td><td>Current Version</td><td>Status</td><td>Date Checked</td><td>Date Changed</td></tr>";
$result = $db->query('SELECT * FROM mobile_version');
foreach($result as $row)
{
print "<tr><td>".$row['gameid']."</td>";
print "<td>".$row['game_name']."</td>";
print "<td>".$row['approved_version']."</td>";
print "<td>".$row['current_version']."</td>";
print "<td>".$row['status']."</td>";
print "<td>".$row['date_checked']."</td>";
print "<td>".$row['date_changed']."</td>";
}
print "</table>";
$db = NULL;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
My aim is to change just the cell with the data in column 'status'. Red if it equals UNAPPROVED and green if it equals APPROVED. Any help would be awesome! Data is in a single table in an sqlite3 database.
You can do it by adding the class to td and add style to that class.
In PHP
print "<td class=".$row['status'].">".$row['status']."</td>";
In CSS
td.APPROVED {
background-color: green;
color: white;
}
td.UNAPPROVED {
background-color: red;
color: white;
}
i need to filter an array and spilt them into different arrays. Here the actual working and slow code:
-----> http://viper-7.com/GVRbVp
but that method is still slow, i think. At least 3 loops...
i would like to scan one time only the array and create array on the fly, i tried with this:
$stray = json_decode('[{"id":"1","zona":"Pescara"},{"id":"2","zona":"Pescara"},{"id":"3","zona":"Teramo"},{"id":"4","zona":"Pescara"},{"id":"5","zona":"Pescara"},{"id":"6","zona":"Teramo"},{"id":"7","zona":"Pescara"},{"id":"8","zona":"Pescara"},{"id":"9","zona":"Pescara"},{"id":"10","zona":"Pescara"},{"id":"11","zona":"Pescara"},{"id":"12","zona":"Pescara"},{"id":"13","zona":"Teramo"},{"id":"14","zona":"Chieti"},{"id":"15","zona":"Chieti"},{"id":"16","zona":"Aquila"},{"id":"17","zona":"Chieti"},{"id":"18","zona":"Chieti"},{"id":"19","zona":"Chieti"},{"id":"20","zona":"Chieti"},{"id":"21","zona":"Campobasso"},{"id":"22","zona":"Aquila"},{"id":"23","zona":"Pescara"},{"id":"24","zona":"Pescara"},{"id":"25","zona":"Pescara"},{"id":"26","zona":"Pescara"},{"id":"27","zona":"Chieti"},{"id":"28","zona":"Pescara"},{"id":"29","zona":"Pescara"},{"id":"30","zona":"Chieti"},{"id":"31","zona":"Pescara"},{"id":"32","zona":"Chieti"},{"id":"33","zona":"Teramo"},{"id":"34","zona":"Teramo"},{"id":"35","zona":"Teramo"},{"id":"37","zona":"Teramo"},{"id":"39","zona":"Pescara"}]',true);
$all_cat = array();
foreach($stray as $row) {
$item_cat = $row['zona'];
if($$cat) { /* check if the category array exist */
$cat = array(); /* if not, create array */
if( !in_array($item_cat,$$item_cat) ) { /* and add the value */
array_push($$item_cat,$row);
}
array_push($all_cat, $cat); /* add new category to index of categories */
} else {
if( !in_array($item_cat,$$item_cat) ) { /* Otherwise just add the value */
array_push($$item_cat,$row);
}
}
}
echo '<pre>'.print_r($cat,true).'</pre>';
If I understand correctly, you could simplify it to
foreach($stray as $row) {
if(!isset($$row['zona'])) {
$$row['zona']=array();
}
${$row['zona']}[] = $row;
}
so now your viper-7 would look like
$stray = json_decode(...[removed to simplify]...,true);
foreach($stray as $row) {
if(!isset($$row['zona'])) {
$$row['zona']=array();
}
${$row['zona']}[] = $row;
}
echo 'Pescara :<pre style="max-height: 50px; overflow: auto">'.print_r($Pescara,true).'</pre>';
echo 'Teramo :<pre style="max-height: 50px; overflow: auto">'.print_r($Teramo,true).'</pre>';
echo 'Chieti :<pre style="max-height: 50px; overflow: auto">'.print_r($Chieti,true).'</pre>';
echo 'Aquila :<pre style="max-height: 50px; overflow: auto">'.print_r($Aquila,true).'</pre>';
echo 'Campobasso :<pre style="max-height: 50px; overflow: auto">'.print_r($Campobasso,true).'</pre>';
For loop through the array. For every element do if else checking for all 3 "zona". If it matches one push it to the respective array within the if and move on to the next element in the array.
I've printed all the data from the database, but my main problem is how to design my data.
I have a table named post_tbl and columns(post_id,post_message,post_date)
this is my query:
$query = "SELECT `post_id`,`post_message` FROM `post_tbl` ORDER BY `post_date`;
This is how I print in php:
if($query_run = mysql_query($query))
{
while($query_row = mysql_fetch_assoc($query_run))
{
$ex_post_id = $query_row['post_id'];
$ex_post_message = $query_row['user_name'];
$ex_post_date= $query_row['post_date'];
echo $ex_post_message;
}
}
how do I make my ex_post_message have a unfirom border and width using html and css? pls help. thanks
if($query_run = mysql_query($query))
{
while($query_row = mysql_fetch_assoc($query_run))
{
$arrMaster[] = $ex_post_message;
}
}
foreach ($arrMaster as $key => $value)
{
if($i==0)
{
$table1.="<tr>";
foreach ($value as $keyc => $valuec)
{
$table1.="<th>".$keyc."</th>";
}
$table1.="</tr>";
$i=1;
}
$table1.="<tr>";
foreach ($value as $keyc => $valuec)
{
$table1.="<td>".$valuec."</td>";
}
$table1.="</tr>";
}
$table1 .= "</table>";
echo $table1;
at this way you can add any style to your table or any class
Yes you can echo HTML element like:
echo "<div class='classname1'>" . $ex_post_message . "</div>";
Then the class classname1 should handle the design. Like the following:
<style>
.classname1{
width: 100px;
height: 30px;
border: 1px solid blackl
}
</style>
There are many ways to achieve this. The one that I've provided is just an example.
I'm building a menu with submenus.
I'm using jQuery to show / hide submenus and I'm using PHP to receive the table values...
To put it in a nutshell, jQuery is there for visual effects, and php is used to show the right menu / submenu values from my database.
But I'm having some trouble here. When I click the menu link, only one submenu, the first one, shows,.
What can i do to show all the submenus?
I disabled jQuery many times, and it shows all the submenus when the jQuery script is disabled.
Menu View
<?php
function menu($url,$name){
echo "
<ul>
<li class='Item1'><a>$name</a></li>
<ul class='submenu'>
";
}
?>
<?php
function submenu($suburl,$subname){
echo "
<li class='menuitem'><a>$subname</a></li>
</ul>
</ul>
";
}
?>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style>
li{
float:left;
display:inline;
margin-left: 50px;
}
.menuitem{
display:none;
}
</style>
<script>
jQuery(function () {
$('.Item1 a').click(function () {
$(this).parent().next().children('.menuitem').toggle();
});
})
</script>
Menu Model
<?php
include(PATH_PUBLIC . '/admin/modules/menu/view/menu_view.php');
function menuModel()
{
connect();
$menu = ("SELECT * FROM menu");
$val = DB_array($menu, 'a+');
$ii = count($val);
$ii = $ii - 1;
for ($i = 0; $i <= $ii; $i++) {
$name = $val[$i]['friendlyname'];
$url = $val[$i]['url'];
$id = $val[$i]['menu_id'];
menu($url, $name);
$submenu = ("SELECT * FROM submenu WHERE menu_id=$id");
$valor = DB_array($submenu, 'a+');
$qq = count($valor);
$qq = $qq - 1;
for ($q = 0; $q <= $qq; $q++) {
$subname = $valor[$q]['name'];
$suburl = $valor[$q]['url'];
submenu($suburl, $subname);
}
}
}
?>
The problem relies in your submenu() function. Suppose that a menu item has 4 submenus. While in the first submenu, when submenu() is executed for the first time, you close both <ul> elements, which means that 2nd, 3rd and 4rth submenus are outside of the lists.
Change you submenu() function to
function submenu($suburl,$subname){
echo "<li class='menuitem'><a>$subname</a></li>";
}
And close the <ul>s just after exiting the second for
......
for ($q = 0; $q <= $qq; $q++) {
$subname = $valor[$q]['name'];
$suburl = $valor[$q]['url'];
submenu($suburl, $subname);
}
echo '</ul></ul>';
}
Question
I have a fairly static website with just a few basic PHP usage. Now the customer would like to have this website translated. I do have a solution, but it's cumbersome and I was wondering how others are doing it and what is the standard (in frameworks, etc.).
My Way
My way (I have simplified it a bit for the sake of easier understanding): I generate a PHP array for each language from the database and store this array in a language file, like es.php for Spanish.
I then translate a string in HTML using a tr function like this:
Before:<h1>Hello World</h1>
After: <h1><?php echo tr('Hello World'); ?></h1> which gives <h1>Hola Mundo</h1> for Spanish.
The Problem
This is cumbersome and error prone. I have to go through each .php file and replace all the hardcoded strings with this PHP tag with echo.
Is there a better way? How are others doing it? If needed, I can elaborate on my implementation.
You should look into the PHP GETTEXT extension, it is very fast and will scan your PHP files for strings to translate with .MO and .PO files
You then can simply do something like __('Hello World'); or if you already have all the strings with tr('Hello World'); then you could just modify the tr function to pass it through __(string) or gettext(string) like..
function tr($string){
__($string)
}
A little late for you, I suppose but in case someone like me stumbles across this thread... Because I currently have the same problem you do.
Unfortunately, there doesn't appear to be a "non-cumbersome way" to do this with PHP. Everything seems to involve lots of function-calls (if you have a lot of text).
Well... there is ONE convenient way. Not exactly safe though. Manipulating the output buffer before it's sent to the user:
=> http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide
So you could depending on the language chosen just define an array filled with "from->to"-data and replace all the readable text in your buffer by looping through that.
But of course... if you e.g. replace "send" (English) with "senden" (German) and you link to a "send.html", it would break that link.
So if one has to translate not only long, definitely unique strings but also shorter ones, one would have to manipulate only the text that is readable to the user. There is a solution for that too - however, that is JavaScript based:
=> http://www.isogenicengine.com/documentation/jquery-multi-language-site-plugin/
You could always punt and translate your site using Google's Tools and Resources.
Generally, I consider a multilingual site no longer to be "static". I use Drupal to implement sites. It has some excellent internationalization options.
Try this solution. It works for me. It has french and english translation.
Index.php
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>How to Translate your Site in Runtime using Jquery - demo</title>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="example">
<h3>How to Translate your Site in Runtime using Jquery - demo</h3>
<div id="content">
<div class="lang_switcher">
<button id="en" class="lang">EN</button>
<button id="fr" class="lang">FR</button>
</div>
<div style="clear:both;"></div>
<!-- nav menu start -->
<ul id="nav">
<li>Home</li>
<li>Peoples >>
<ul>
<li>All list</li>
<li>Online</li>
</ul>
</li>
<li>Articles >>
<ul>
<li>JavaScript</li>
<li>PHP</li>
<li>HTML</li>
<li>CSS</li>
</ul>
</li>
<li>Contact us</li>
</ul>
<!-- nav menu end -->
<div style="clear:both;"></div>
<h2 key="welcome" class="tr">Welcome guests</h2>
<hr />
<div key="a_man" class="tr">A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.</div>
</div>
</div>
</body>
</html>
main.js
// preparing language file
var aLangKeys=new Array();
aLangKeys['en']=new Array();
aLangKeys['fr']=new Array();
aLangKeys['en']['home']='Home';
aLangKeys['en']['peoples']='Peoples >>';
aLangKeys['en']['all_list']='All list';
aLangKeys['en']['online']='Online';
aLangKeys['en']['articles']='Articles >>';
aLangKeys['en']['js']='JavaScript';
aLangKeys['en']['php']='PHP';
aLangKeys['en']['html']='HTML';
aLangKeys['en']['css']='CSS';
aLangKeys['en']['contact_us']='Contact us';
aLangKeys['en']['welcome']='Welcome guests';
aLangKeys['en']['a_man']='A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.';
aLangKeys['fr']['home']='Accueil';
aLangKeys['fr']['peoples']='Peuples >>';
aLangKeys['fr']['all_list']='Toutes les listes';
aLangKeys['fr']['online']='En ligne';
aLangKeys['fr']['articles']='Articles >>';
aLangKeys['fr']['js']='JavaScript';
aLangKeys['fr']['php']='Php';
aLangKeys['fr']['html']='Html';
aLangKeys['fr']['css']='Css';
aLangKeys['fr']['contact_us']='Contactez nous';
aLangKeys['fr']['welcome']='Bienvenue aux invites';
aLangKeys['fr']['a_man']="Un homme soudoie un lapin avec des prothèses méchantes pour s'enfuir avec lui dans un voilier via une ambulance. Corruption des Koalas pour qu'ils restent illégalement à un endroit. Les arbres m'ancrent en place. / Votre mère conduit l'ambulance, mais la ville est plus loin qu'il n'y paraît.";
$(document).ready(function() {
// onclick behavior
$('.lang').click( function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i){
$(this).text(aLangKeys[lang][ $(this).attr('key') ]);
});
} );
});
And some css- main.css
body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.example{background:#FFF;width:500px;height:500px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius:3px;-webkit-border-radius:3px}
.lang_switcher{float:right;overflow:hidden;}
/* nav menu styles */
#nav,#nav ul{list-style:none;font:10px verdana, sans-serif;border:1px solid #000;background:#fff;position:relative;z-index:200;border-color:#eca #b97 #a86 #edb;border-width:1px 2px 2px 1px;margin:0;padding:0 0 5px}
#nav{height:25px;padding:0}
#nav table{border-collapse:collapse}
#nav li{float:left;padding:0 20px 0 10px}
#nav li li{float:none}
#nav li a li{float:left}
#nav li a{display:block;float:left;color:#888;height:25px;padding-right:5px;line-height:25px;text-decoration:none;white-space:nowrap}
#nav li li a{height:20px;line-height:20px;float:none}
#nav li:hover{position:relative;z-index:300;background:#fff}
#nav a:hover{position:relative;z-index:300;text-decoration:underline;color:#b75}
#nav :hover ul{left:0;top:22px}
#nav a:hover ul{left:-10px}
#nav li:hover li:hover > ul{left:-15px;margin-left:100%;top:-1px}
#nav li:hover > ul ul{position:absolute;left:-9999px;top:-9999px;width:auto}
#nav li:hover > a{text-decoration:underline;color:#b75}
#nav a:hover a:hover ul,#nav a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover a:hover ul{left:100%;top:-1px}
#nav ul,#nav a:hover ul ul,#nav a:hover a:hover ul ul,#nav a:hover a:hover a:hover ul ul,#nav a:hover a:hover a:hover a:hover ul ul{position:absolute;left:-9999px;top:-9999px}
Do way i translate my website is
Under doctype have lang then your selected lang, eg below,
Then create a php function to get this by $_POST['get'],
and have have that function load up the selected language file/db etc,
I made a class to do mine
class WILang
{
function __construct()
{
$this->WIdb = WIdb::getInstance();
}
public static function all($jsonEncode = true) {
// determine lanuage
$language = self::getLanguage();
//echo $language;
$WIdb = WIdb::getInstance();
//$file = WILang::getFile($language);
//echo $file;
//echo $language;
if ( ! self::isValidLanguage($language) )
die('Language file doesn\'t exist!');
else {
$sql = "SELECT * FROM `wi_trans` WHERE `lang` = :file";
$query = $WIdb->prepare($sql);
$query->bindParam(':file', $language, PDO::PARAM_STR);
$query->execute();
//$result = array();
while ($result = $query->fetchAll(PDO::FETCH_ASSOC)) {
echo "{";
foreach ($result as $res) {
echo '"' .$res['keyword'] .'":"' . $res['translation'] . '",';
//return array($res['keyword'] => $res['translation'] ,);
}
echo "}";
}
}
}
public static function get($key ) //, $bindings = array()
{
// determine language
$language = self::getLanguage();
$WIdb = WIdb::getInstance();
$sql = "SELECT * FROM `wi_trans` WHERE `keyword`=:key AND lang=:lang";
$query = $WIdb->prepare($sql);
$query->bindParam(':key', $key, PDO::PARAM_STR);
$query->bindParam(':lang', $language, PDO::PARAM_STR);
$query->execute();
$res = $query->fetch(PDO::FETCH_ASSOC);
if($res > 0)
return $res['translation'];
else
return '';
}
public static function setLanguage($language)
{
// check if language is valid
if ( self::isValidLanguage($language) ) {
//set language cookie to 1 year
setcookie('wi_lang', $language, time() + 60 * 60 * 24 * 365, '/');
// update session
WISession::set('wi_lang', $language);
//refresh the page
header('Location: ' . $_SERVER['PHP_SELF']);
}
}
public static function getLanguage()
{
// check if cookie exist and language value in cookie is valid
if ( isset ( $_COOKIE['wi_lang'] ) && self::isValidLanguage ( $_COOKIE['wi_lang'] ) )
return $_COOKIE['wi_lang']; // return lang from cookie
else
return WISession::get('wi_lang', DEFAULT_LANGUAGE);
}
private static function getTrans($language)
{
$WIdb = WIdb::getInstance();
//$file = WILang::getFile($language);
//echo $file;
//echo $language;
if ( ! self::isValidLanguage($language) )
die('Language file doesn\'t exist!');
else {
//$language = include $file;
//return $language;
$sql = "SELECT * FROM `wi_trans` WHERE `lang` = :file";
$query = $WIdb->prepare($sql);
$query->bindParam(':file', $language, PDO::PARAM_STR);
$query->execute();
//$result = array();
while ($result = $query->fetchAll(PDO::FETCH_ASSOC)) {
echo "{";
foreach ($result as $res) {
echo '"' .$res['keyword'] .'":"' . $res['translation'] . '",';
//return array($res['keyword'] => $res['translation'] ,);
}
echo "}";
}
}
}
private static function getFile($language)
{
$WIdb = WIdb::getInstance();
$sql = "SELECT * FROM `wi_lang` WHERE `lang` = :file";
$query = $WIdb->prepare($sql);
$query->bindParam(':file', $language, PDO::PARAM_STR);
$query->execute();
$res = $query->fetch(PDO::FETCH_ASSOC);
//echo $res['lang'];
if ($res > 0)
return $res['lang'];
else
return '';
}
private static function isValidLanguage($lang)
{
$file = self::getFile($lang);
//echo $file;
if($file == "")
//if ( ! file_exists( $file ) )
return false;
else
return true;
}
}