I have the below code, so the user can select the language he desire:
<label style="float: left; width: 50%;" for="system_language">Select Language:</label>
<select id="system_language" class="selectbox float-right" onChange="switchLanguageLogin(); ">
<? echo getLanguageList(); ?>
</select>
This is the function of the languages!
function loadLanguage($lng, $units = '')
{
global $ms, $la, $gsValues;
// always load main english language to prevet error if something is not translated in another language
include ($gsValues['PATH_ROOT'].'lng/english/lng_main.php');
// load another language
if ($lng != 'english')
{
$lng = $gsValues['PATH_ROOT'].'lng/'.$lng.'/lng_main.php';
if (file_exists($lng))
{
include($lng);
}
}
Added the Language Function
function getLanguageList()
{
global $ms, $gsValues;
$result = '';
$languages = array();
$q = "SELECT * FROM `gs_system` WHERE `key`='LANGUAGES'";
$r = mysqli_query($ms, $q);
$row = mysqli_fetch_array($r);
$languages = explode(",", $row['value']);
array_unshift($languages , 'english');
foreach ($languages as $value)
{
if ($value != '')
{
$result .= '<option value="'.$value.'">'.ucfirst($value).'</option>';
}
}
return $result;
}
The first (and default) option on the dropdown menu is English. The problem is that if I choose Spanish, it translates to Spanish, but on the dropdowm menu it leaves the default value which is English. This concludes that the page is in Spanish, but the value from the dropdown shows "English".
How can i solve this?
You do not use your $lng variable in the global scope, so it is not visible for your function. A solution would therefore be to provide the selected language as parameter to the getLanguageList function and set the equal value as selected:
function getLanguageList($selected = 'english') {
//...
foreach ($languages as $value) {
if ($value !== '') {
$result .= '<option value="'.$value.'" ' . ($selected === $value ? ' selected="selected"' : ''). '>' . ucfirst($value) . '</option>';
}
}
//...
}
Like this the selection is kept for the dropdown and therefore for the HTML.
In your view you would then need to provide $lng and call <? echo getLanguageList($lng); ?>.
Check in your init.php file should have a comment
// gets language from cookies
If there is not such comment, write it just before MySQL connection and add the following code after it
if (isset($_COOKIE['gs_language']))
{
$gsValues['LANGUAGE'] = $_COOKIE['gs_language'];
}
else
{
$expire = time() + 2592000;
setcookie('gs_language', $gsValues['LANGUAGE'], $expire, '/');
}
// puts selected language into cookies
if (isset($_GET['lng']))
{
$gsValues['LANGUAGE'] = $_GET['lng'];
$expire = time() + 2592000;
setcookie('gs_language', $gsValues['LANGUAGE'], $expire, '/');
}
Then go to fn_common.php file and change the getLanguageList function to
function getLanguageList()
{
global $ms, $gsValues;
$result = '';
$languages = array();
$q = "SELECT * FROM `gs_system` WHERE `key`='LANGUAGES'";
$r = mysqli_query($ms, $q);
$row = mysqli_fetch_array($r);
$languages = explode(",", $row['value']);
array_unshift($languages , 'english');
$currentLang = $gsValues['LANGUAGE'];
foreach ($languages as $value)
{
if ($value != '')
{
$result .= '<option value="'.$value.'" ' . ($currentLang === $value ? ' selected="selected"' : ''). '>' . ucfirst($value) . '</option>';
}
}
return $result;
}
Related
I need two print the same rows which retrieved from the db, in two different locations in same php file.
I know it is better to have a function. It tried, It doesn't work properly.
I am using the below code print the said rows/
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
I need to print exactly the same code twice in two different location in a php file.
I think it is not a good idea to retrieve data twice from the server by pasting the above code twice.
Is there any way to recall or reprint the retrieved data in second place which I need to print.
Edit : Or else, if someone can help me to convert this to a function?
I converted this into a function. It prints only first row.
Edit 2 : Following is my function
unction getGroup($dbconn)
{
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($dbconn ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$groupData = "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
return $groupData;
You can store the records coming from the DB in array and use a custom function to render the element
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
$options = []; //store in an array
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$options[$groups['profile_gid']] = $groups['profile_gname'];
}
}
Now you can use the $options array many times in your page
echo renderElement($options);
function renderElement($ops){
$html = '';
foreach($ops as $k => $v){
$html .= "<option value={$k}>{$v}</option>";
}
return $html;
}
If the data is same for both places, put the entire string into variable, then echo it on those two places.
instead of
echo "here\n";
echo "there\n";
do
$output = "here\n";
$output .= "there\n";
then somewhere
echo $output
on two places....
Values are being stored in groups array, hence you can use a foreach loop elsewhere to get values from the array:
$groups = array();
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
// use here
foreach($groups as $group)
{
echo $group['profile_gid'] . " ". $group['profile_gname'] . "<br/>";
}
class ProfileGroups
{
public $profile_groups_options;
public static function get_profile_groups_options($condb) {
$get_g = "SELECT * FROM profile_groups";
if( isset( $this->profile_groups_options ) && $this->profile_groups_options != '') {
return $this->profile_groups_options;
}
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$this->profile_groups_options .= "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
$this->profile_groups_options .= '<option value="">Empty - No Groups!!</option>';
}
return $this->profile_groups_options;
}
}
ProfileGroups::get_profile_groups_options($condb);
I am using WPML language, and cant find solution for next thing:
On the Language switcher i want to hide language, lets say for example - "he", if current language is lets say for example "ar", so when we on arabic site we will not see on the selector the Hebrew, and same thing if we on Hebrew, the arabic will not display.
On shorten words: what i want is - if we on arabic site - the hebrew flag will be hidden.
What i tried:
function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0');
if(!empty($languages)){
if(ICL_LANGUAGE_CODE=='en')
{
$order = array('ar'); //Specify your sort order here
}
elseif(ICL_LANGUAGE_CODE=='he')
{
$order = array('en', 'ar'); //Specify your sort order here
}
foreach ($order as $l) {
if (isset($languages[$l])) {
$l = $languages[$l]; //grab this language from the unsorted array that is returned by icl_get_languages()
//Display whatever way you want -- I'm just displaying flags in anchors (CSS: a {float:left; display:block;width:18px;height:12px;margin:0 2px;overflow:hidden;line-height:100px;})
if($l['active']) { $class = "active"; $url=""; } else { $class = ''; $url = 'href="'.$l['url'].'"'; }
echo '<a '.$url.' style="background:url('.$l['country_flag_url'].') no-repeat;" class="flag '.$class.'">';
echo $l['language_code'].'';
}
}
}
}
Its not affect at all the selector.
You can check out the plugin WPML Flag In Menu.
You could use the plugin_wpml_flag_in_menu() function from the plugin (see source code here) and replace:
// Exclude current viewing language
if( $l['language_code'] != ICL_LANGUAGE_CODE )
{
// ...
}
with
// Include only the current language
if( $l['language_code'] == ICL_LANGUAGE_CODE )
{
// ...
}
to show only the current language/flag, if I understand you correctly.
ps: If you need further assistance, you could for exampe show us the output of this debug function for the active language:
function debug_icl_active_language()
{
$languages = icl_get_languages( 'skip_missing=0' );
foreach( (array) $languages as $l )
{
if( $l['active'] )
{
printf( '<pre> Total languages: %d - Active: %s </pre>',
count( $languages ),
print_r( $l, TRUE ) );
}
}
}
i have some useful link for you, please go through it first:
http://wpml.org/forums/topic/hide-language-vs-display-hidden-languages-in-your-profile-not-working/
http://wpml.org/forums/topic/hide-one-language/
http://wpml.org/forums/topic/hiding-active-language-in-menu/
http://wpml.org/forums/topic/language-selector-how-to-hide-one-language/
thanks
function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0');
if(!empty($languages)){
$filter = array();
$filter['ar'] = array( 'he' );
// set your other filters here
$active_language = null;
foreach ($languages as $l)
if($l['active']) {
$active_language = $l['language_code'];
break;
}
$filter = $active_language && isset( $filter[$active_language] ) ? $filter[$active_language] : array();
foreach ($languages as $l) {
//Display whatever way you want -- I'm just displaying flags in anchors (CSS: a {float:left; display:block;width:18px;height:12px;margin:0 2px;overflow:hidden;line-height:100px;})
if( in_array( $l['language_code'], $filter) )
continue;
if($l['active']) { $class = "active"; $url=""; } else { $class = ''; $url = 'href="'.$l['url'].'"'; }
echo '<a '.$url.' class="flag '.$class.'"><img src="', $l['country_flag_url'], '" alt="', esc_attr( $l['language_code'] ), '" /></a>';
}
}
}
EDIT: If I get this right, your client(I assume) doesn't want his customers (Israelis especiay) to know that he offer service also to the arabic speaking cusomers. If it so then you can parse the Accept-Language header and filter the language selector according the result.
I have a similar problem/issue:
On this website: https://neu.member-diving.com/
I have languages I not need in the switcher. I tried the code above, but it nothing changed so far.
So, what I would like to do is, When a client is on the one "german" page, the other german languages in the switcher should not need to be there, only the english one and the actual german one.
Where do I need to put code like
function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0');
if(!empty($languages)){
$filter = array();
$filter['ar'] = array( 'he' );
// set your other filters here
$active_language = null;
foreach ($languages as $l)
if($l['active']) {
$active_language = $l['language_code'];
break;
}
$filter = $active_language && isset( $filter[$active_language] ) ? $filter[$active_language] : array();
foreach ($languages as $l) {
//Display whatever way you want -- I'm just displaying flags in anchors (CSS: a {float:left; display:block;width:18px;height:12px;margin:0 2px;overflow:hidden;line-height:100px;})
if( in_array( $l['language_code'], $filter) )
continue;
if($l['active']) { $class = "active"; $url=""; } else { $class = ''; $url = 'href="'.$l['url'].'"'; }
echo '<a '.$url.' class="flag '.$class.'"><img src="', $l['country_flag_url'], '" alt="', esc_attr( $l['language_code'] ), '" /></a>';
}
}
}
I am working with a PHP/MySQL script for managing our domain portfolio. I am trying to modify a dropdown field in a form to convert if to a checkbox table.
Currently the dropdown propagates with all of our category variables and I would need the checkbox menu to do the same thing but display all the categories at once.
This is the current code for the dropdown:
<select name="category[]" id="category" multiple="multiple"
style="width:400px; height:1500px;"> <?php echo
build_select('category'); ?></select>
An example of the page in action is here user: demo pass: demo
Build_select code:
enter code herefunction is ($option, $value)
{
global $db;
switch ($option)
{
case 'orderby':
if (!in_array($value, array('domain', 'category', 'registrar', 'regdate', 'expiry', 'price', 'status')))
{
return 'domain';
}
break;
case 'catid':
if (is_string($value))
{
return NULL;
}
else if (is_integer($value) AND !is('category', $value))
{
return NULL;
}
break;
case 'email':
return (bool)(preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+#([0-9.]+|([^\s\'"<>]+\.+[a-z]{2,6}))$#si', $value));
break;
case 'injection':
return (bool)(preg_match('#(To:|Bcc:|Cc:|Content-type:|Mime-version:|Content-Transfer-Encoding:)#i', urldecode($value)));
break;
case 'spam':
preg_match_all('#(<a href|\[url|http[s]?://)#i', $value, $matches, PREG_PATTERN_ORDER);
return (bool)(count($matches[0]) > 2);
break;
case 'domain':
$getdomain = $db->query("
SELECT *
FROM " . TABLE_PREFIX . "domains
WHERE " . (is_numeric($value) ? "domainid = " . intval($value) : "domain = '$value'") . "
");
$numrows = $db->num_rows($getdomain);
$db->free_result($getdomain);
return (bool)($numrows > 0);
break;
case 'category':
if (is_numeric($value) AND $value == 0)
{
return true;
}
$getcategory = $db->query("
SELECT *
FROM " . TABLE_PREFIX . "categories
WHERE " . (is_numeric($value) ? "catid = " . intval($value) : "title = '$category'") . "
");
$numrows = $db->num_rows($getcategory);
$db->free_result($getcategory);
return (bool)($numrows > 0);
break;
case 'expdate':
$value = str_replace('-', '/', $value);
You will need an
<input type='checkbox' name="category[]" value='valueToPassInCategory' />
for every element. Your build_select should be edited to do this. No select is required anymore.
Problem:
I am trying to delete all sublevels of a category by using a class. Currently I can only make it delete two sublevels, not three.
The database table:
CREATE TABLE betyg_category (
CID int(11) NOT NULL AUTO_INCREMENT,
Item varchar(100) NOT NULL,
Parent int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (CID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The PHP class:
<?php
class ItemTree
{
var $itemlist = array();
function ItemTree($query)
{
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$this->itemlist[$row['CID']] = array(
'name' => $row['Name'],
'parent' => $row['Parent']
);
}
}
function get_tree($parent, $with_parent=0)
{
$item_tree = array();
if ($with_parent == 1 && $parent != 0)
{
$item_tree[$parent]['name'] = $this->itemlist[$parent]['name'];
$item_tree[$parent]['parent'] = $this->itemlist[$parent]['parent'];
$item_tree[$parent]['child'] = $this->get_tree($parent);
return $item_tree;
}
foreach ($this->itemlist as $key => $val)
{
if ($val['parent'] == $parent)
{
$item_tree[$key]['name'] = $val['name'];
$item_tree[$key]['parent'] = $val['parent'];
$item_tree[$key]['child'] = $this->get_tree($key);
}
}
return $item_tree;
}
function make_optionlist ($id, $class='', $delimiter='/')
{
$option_list = '';
$item_tree = $this->get_tree(0);
$options = $this->make_options($item_tree, '', $delimiter);
if (!is_array($id))
{
$id = array($id);
}
foreach($options as $row)
{
list($index, $text) = $row;
$selected = in_array($index, $id) ? ' selected="selected"' : '';
$option_list .= "<option value=\"$index\" class=\"$class\"$selected>$text</option>\n";
}
return $option_list;
}
function make_options ($item_tree, $before, $delimiter='/')
{
$before .= empty($before) ? '' : $delimiter;
$options = array();
foreach ($item_tree as $key => $val)
{
$options[] = array($key, '- '.$before.$val['name']);
if (!empty($val['child'])) {
$options = array_merge($options, $this->make_options($val['child'], $before.$val['name'], $delimiter));
}
}
return $options;
}
function get_navlinks ($navid, $tpl, $startlink='', $delimiter=' ยป ')
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$navlink = array();
while (isset($this->itemlist[$navid]))
{
$replace = array($navid, $this->itemlist[$navid]['name']);
$navlink[] = str_replace($search, $replace, $tpl);
$navid = $this->itemlist[$navid]['parent'];
}
if (!empty($startlink))
{
$navlink[] = str_replace($search, array(0, $startlink), $tpl);
}
$navlink = array_reverse($navlink);
return implode($delimiter, $navlink);
}
function show_tree ($parent=0, $tpl='%s', $ul_class='', $li_class='')
{
$item_tree = $this->get_tree($parent);
return $this->get_node($item_tree, $parent, $tpl, $ul_class, $li_class);
}
function get_node ($item_tree, $parent, $tpl, $ul_class, $li_class)
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$output = "\n<ul class=\"$ul_class\">\n";
foreach ($item_tree as $id => $item)
{
$replace = array($id, $item['name']);
$output .= "<li class=\"$li_class\">".str_replace($search, $replace, $tpl);
$output .= !empty($item['child']) ? "<br />".$this->get_node ($item['child'], $id, $tpl, $ul_class, $li_class) : '';
$output .= "</li>\n";
}
return $output . "</ul>\n";
}
function get_id_in_node ($id)
{
$id_list = array($id);
if (isset($this->itemlist[$id]))
{
foreach ($this->itemlist as $key => $row)
{
if ($row['parent'] == $id)
{
if (!empty($row['child']))
{
$id_list = array_merge($id_list, get_id_in_node($key));
} else
{
$id_list[] = $key;
}
}
}
}
return $id_list;
}
function get_parent ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['parent'] : false;
}
function get_item_name ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['name'] : false;
}
}
?>
Scenario:
Say you have the following structure in a :
Literature
-- Integration of sources
---- Test 1
It will result in the following in the database table:
When I try to delete this sublevel, it will leave the last sublevel in the database while it should delete it. The result will be:
The PHP code:
//Check if delete button is set
if (isset($_POST['submit-deletecategory']))
{
//Get $_POST variables for category id
$CategoryParent = intval($_POST['CategoryList']);
//Check if category is selected
if ($CategoryParent != "#")
{
//Get parent category and subsequent child categories
$query = "SELECT CID, Item AS Name, Parent FROM " . TB_CATEGORY . " ORDER BY Name";
$items = new ItemTree($query);
if ($items->get_item_name($_POST['CategoryList']) !== false)
{
//Build up erase list
$CategoryErase = $items->get_id_in_node($CategoryParent);
$CategoryEraseList = implode(", ", $CategoryErase);
}
else
{
$CategoryEraseList = 0;
}
//Remove categories from database
$query = "DELETE FROM " . TB_CATEGORY . " WHERE CID IN ($CategoryEraseList)";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
//Return a confirmation notice
header("Location: settings.php");
exit;
}
}
Thank you in advance for any guidance I can get to solve the issue.
Here is a way to do it : use a recursive function, which will first look for the leaf item (the deepest in your tree). You remove children first, then the parent. And for each child, you remove child's children first, etc...
deleteSub(1);
function deleteSub($cat_id) {
$request = "SELECT * FROM ". TB_CATEGORY ." WHERE Parent = ".$cat_id;
$results = mysql_query($request);
while($child = mysql_fetch_array($results))
{
deleteSub($child["CID"]);
}
$request = "DELETE FROM ". TB_CATEGORY ." WHERE CID = ".$cat_id;
return mysql_query($request);
}
A better way could be use this kind of recursive function to store CIDs in an array, then make a single DELETE request, but I think you'll be able to adapt this code.
I'm not going to read or try to understand the entire code, but it seems to me you need some sort of recursion function. What I basicly would do is create a function that goes up in the hierachy and one that goes down.
Note: It has been a while since i've written anything in procedural mysql, so please check if the mysql_num_rows(),mysql_fetch_array and so on is written in the correct manner
EDIT: I've just noticed you only wanted a downwards deletion and therefore zessx's answer is more valid
<?php
function recursiveParent($id) {
$sql = 'SELECT parent FROM betyg_category WHERE CID=' . $id;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveParent($r['parent']);
}
}
$sql = 'DELETE FROM betyg_category WHERE CID=' . $id;
mysql_query($sql);
}
function recursiveChild($parent) {
$sql = 'SELECT CID FROM betyg_category WHERE parent=' . $parent;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveChild($r['CID']);
}
}
$sql = 'DELETE FROM betyg_category WHERE parent=' . $parent;
mysql_query($sql);
}
function delete($id) {
recursiveParent($id);
recursiveChild($id);
}
?>
This is my way to do. instead of recursive the query to run, i get all the child's id first then only run query. here the code refer:-
First, defined a variable called $delete_node_list as array. (to store all node id that need to be delete)
function delete_child_nodes($node_id)
{
$childs_node = $this->edirectory_model->get_child_nodes($node_id);
if(!empty($childs_node))
{
foreach($childs_node as $node)
{
$this->delete_child_nodes($node['id']);
}
}
$this->delete_node_list[] = $node_id;
}
in mysql..
$sql = 'DELETE FROM betyg_category WHERE CID IN '.$this->delete_node_list;
mysql_query($sql);
Out of coffee and brain's given up...
...can anyone help to make this form date dropdown function retain selected month on $_POST ['submit'] or isset($missing) in the case of there being an error/missing field etc
function createMonths($id='month_select', $selected=null)
{
/*** array of months ***/
$months = array(
1=>'Jan',
2=>'Feb',
3=>'Mar',
4=>'Apr',
5=>'May',
6=>'Jun',
7=>'Jul',
8=>'Aug',
9=>'Sep',
10=>'Oct',
11=>'Nov',
12=>'Dec');
/*** current month ***/
$selected = is_null($selected) ? date('m') : $selected;
$select = '<select name="'.$id.'" id="'.$id.'">'."\n";
foreach($months as $key=>$mon)
{
$select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"';
$select .= ($key==$selected) ? ' selected="selected"' : '';
$select .= ">$mon</option>\n";
}
$select .= '</select>';
return $select;
}
In the event you have invalid form data, you should check if the $_POST['month_select'] variable is set and not empty and create your dropdown passing in it's value like so:
$selected = (!empty($_POST['month_select'])) ? $_POST['month_select'] : null;
createMonths('month_select', $selected);
function createMonths($id='month_select', $selected = null)
{
/*** array of months ***/
$months = array(
'01'=>'Jan',
'02'=>'Feb',
'03'=>'Mar',
'04'=>'Apr',
'05'=>'May',
'06'=>'Jun',
'07'=>'Jul',
'08'=>'Aug',
'09'=>'Sep',
'10'=>'Oct',
'11'=>'Nov',
'12'=>'Dec');
/*** current month ***/
$selected = is_null($selected) ? date('n') : $selected;
$select = '<select name="'.$id.'" id="'.$id.'">'."\n";
$select .= "<option value=""></option>\n";
foreach($months as $key => $mon)
{
$select .= '<option value="'.$key.'"';
$select .= ($key == $selected) ? ' selected="selected"' : '';
$select .= ">$mon</option>\n";
}
$select .= '</select>';
return $select;
}
I have also taken the liberty of fixing your createMonths() function by the recommendation regarding date('n') and changing your array keys to strings as this will avoid having to pad your months.