Make php date dropdown function 'sticky' - php

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.

Related

Print same code twice in two locations in one php file

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);

Set selected value on dynamic dropdown list

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;
}

Putting All Top Categories as Optgroup from Category Table in PHP MYSQL

I am half stuck in putting all my top categories into Optgroup, tried several ways, took lot of references from stackoverflow, but failed to achieve as I am required.
Took reference from here and built my nested categories:
function fetchCategoryTree($parent = 0, $spacing = '', $user_tree_array = '') {
global $conn;
if (!is_array($user_tree_array)) {
$user_tree_array = array();
}
$sql = "SELECT `id`, `name`, `parent_id` FROM `acct_categs` WHERE `parent_id` = '".$parent."' ORDER BY `name` ASC";
$query = $conn->Execute($sql);
if (count($query) > 0) {
$current_parent = '';
while ($row = $query->FetchRow()) {
$user_tree_array[] = array("catid" => $row['id'], "catname" => $spacing . $row['name']);
$user_tree_array = fetchCategoryTree($row['id'], $spacing . '- ', $user_tree_array);
}
}
return $user_tree_array;
}
function categoryoption(){
$categoryList = fetchCategoryTree();
$dropdown = '<select name="category_id">';
foreach($categoryList as $cl) {
$dropdown .= "\n<option value=\"".$cl["catid"]."\">".$cl["catname"]."</option>";
}
$dropdown .= "</select>";
return $dropdown;
}
echo categoryoption();
So when I echo this I get the following dropdown:
<select name="category_id">
<option value="91">Assets</option>
<option value="3">- Capital Assets</option>
<option value="23">- - Accum. Amort. -Furn. & Equip.</option>
<option value="25">- - Accum. Amort. -Vehicle</option>
<option value="22">- - Office Furniture & Equipment</option>
<option value="24">- - Vehicle</option>
<option value="1">- Current Assets</option>
<option value="15">- - Accounts Receivables</option>
<option value="16">- - Allowance for doubtful accounts</option>
<option value="13">- - Checking Account</option>
....</select>
What I want is like this, https://jsfiddle.net/sbnzp1wL/
<select name="category_id">
<optgroup label="Assets"></optgroup>
<optgroup label="Capital Assets"></optgroup>
<option value="23">- - Accum. Amort. -Furn. & Equip.</option>
<option value="25">- - Accum. Amort. -Vehicle</option>
<option value="22">- - Office Furniture & Equipment</option>
<option value="24">- - Vehicle</option>
<optgroup label="Current Assets"></optgroup>
<option value="15">- - Accounts Receivables</option>
<option value="16">- - Allowance for doubtful accounts</option>
<option value="13">- - Checking Account</option>
<option value="14">- - Petty Cash</option>
....</select>
I read it's not possible in nested queries within stackoverflow, but I also learnt it's possible from here.
But with that link help, my top categories listed 2nd level categories and 2nd level listed it's children. Somehow, from that also I did not achieve what I wanted as.
My table values are here
Finally got it working as per my need, if someone needs it, am posting it here... All big thanks to #stj (answer accepted and upvoted)
$sql = "SELECT `id`, `name`, `parent_id` FROM `acct_categs` ORDER BY `name` ASC";
$query = $conn->Execute($sql);
// build a lookup array with all elements
$all = array();
$hasChildren = array();
while ($row = $query->FetchRow()) {
$all[$row["id"]] = $row;
$hasChildren[$row["parent_id"]] = true;
}
// recursive processing function
function process($rows, $hasChildren, $parentId, $level = 0) {
foreach ($rows as $id => $row) {
if ($row["parent_id"] === $parentId) {
// this is the element we are looking for
$pad = str_repeat(" ", $level);
if (isset($hasChildren[$id])) {
// the element has children
$line = "\n<optgroup label=\"{$row["name"]}\"></optgroup>";
//$line = $pad . $row["id"] . " - " . $row["name"] . " (has children)";
} else {
// the element does not have any children
$line = "\n<option value=\"{$row["id"]}\">{$row["name"]}</option>";
//$line = $pad . $row["id"] . " - " . $row["name"] . " (no children)";
}
// print it
print $line . "\n";
// finally process the children
if (isset($hasChildren[$id])) {
process($rows, $hasChildren, $id, $level + 1);
}
}
}
}
echo '<select name="category_id">';
// start processing
$print = process($all, $hasChildren, "0");
echo $print;
echo '</select>';
What you are probably looking for is a depth-first recursion that renders your nested data.
I suggest querying all values from the database with a single query and process them in PHP. This saves you from issuing lots of individual database queries (one per element).
Once you've queried all relevant rows, you can walk them in PHP recursively.
Here is some code that will do that.
$sql = "SELECT `id`, `name`, `parent_id` FROM `acct_categs` ORDER BY `name` ASC";
$query = $conn->Execute($sql);
// build a lookup array with all elements
$all = array();
$hasChildren = array();
while ($row = $query->FetchRow()) {
$all[$row["id"]] = $row;
$hasChildren[$row["parent_id"]] = true;
}
// recursive processing function
function process($rows, $hasChildren, $parentId, $level = 0) {
foreach ($rows as $id => $row) {
if ($row["parent_id"] === $parentId) {
// this is the element we are looking for
$pad = str_repeat(" ", $level);
if (isset($hasChildren[$id])) {
// the element has children
$line = $pad . $row["id"] . " - " . $row["name"] . " (has children)";
}
else {
// the element does not have any children
$line = $pad . $row["id"] . " - " . $row["name"] . " (no children)";
}
// print it
print $line . "\n";
// finally process the children
if (isset($hasChildren[$id])) {
process($rows, $hasChildren, $id, $level + 1);
}
}
}
}
// start processing
process($all, $hasChildren, 0);
Note that it won't print nested optgroups. The reason is that I am not sure where the optgroups should go. I think optgroup elements shouldn't be nested. But if you really want to do that, go ahead.
Additionally, you may want to adjust the parts of the code that populates $line to your needs.
Get all cats with parent_id = 0, than loop it, and get childs. Parent category wrapp in <optgroup></optgroup>, child in <option></option>.
Try adding a parent ID check to your $categoryList loop:
function fetchCategoryTree($parent = 0, $spacing = '', $user_tree_array = '') {
global $conn;
if (!is_array($user_tree_array)) {
$user_tree_array = array();
}
$sql = "SELECT `id`, `name`, `parent_id` FROM `acct_categs` WHERE `parent_id` = '".$parent."' ORDER BY `name` ASC";
$query = $conn->Execute($sql);
if (count($query) > 0) {
$current_parent = '';
while ($row = $query->FetchRow()) {
$user_tree_array[] = array("catid" => $row['id'], "catname" => $spacing . $row['name'], "parentid" => $row['parent_id']);
$user_tree_array = fetchCategoryTree($row['id'], $spacing . '- ', $user_tree_array);
}
}
return $user_tree_array;
}
function categoryoption(){
$categoryList = fetchCategoryTree();
$dropdown = '<select name="category_id">';
foreach($categoryList as $cl) {
if ($c1["parentid"] == '0') {
$dropdown .= "\n<optgroup label=\"".$cl["catname"]."\"></optgroup>";
} else {
$dropdown .= "\n<option value=\"".$cl["catid"]."\">".$cl["catname"]."</option>";
}
}
$dropdown .= "</select>";
return $dropdown;
}
echo categoryoption();
I like querying all values at once and ordering them with coalesce. It's the simplest option I've used.
<label>Category<br>
<select name="category_id">
<option value="0"> -- Choose Category -- </option>
<?
//All Categories
$sql = "SELECT id, parent_id, name FROM acct_categs ORDER BY COALESCE((SELECT NULLIF(parent_id,0)), id), NULLIF(parent_id,0)";
$catQuery = $conn->Execute($sql);
if($catQuery->num_rows > 0) {
while($cat = $catQuery->fetch_object()){
if($cat->parentId == 0){
echo '<optgroup label="'.$cat->title.'"></optgoup>';
} else {
echo '<option value="'.$cat->id.'">'.$cat->title.'</option>';
}
}
}
?>
</select>
</label>

Entering multiple selections into database from <select multiple> box

I have the bit of code below and I would like uses to select multiple options in the "select multiple" box and for these all to be added into the database. At the moment only 1 of the values that is selected is entered. I am a noob with this sort of thing so an in need of help to progress with the project.
Thanks for any help!
function ProjectTheme_get_categories($taxo, $selected = "", $include_empty_option = "", $ccc = "")
{
$args = "orderby=name&order=ASC&hide_empty=0&parent=0";
$terms = get_terms( $taxo, $args );
$ret = '<select multiple size="20" name="'.$taxo.'_cat" class="'.$ccc.'" id="scrollselect '.$ccc.'">';
if(!empty($include_empty_option)) $ret .= "<option value=''>".$include_empty_option."</o ption>";
if(empty($selected)) $selected = -1;
foreach ( $terms as $term )
{
$id = $term->term_id;
$ret .= '<option '.($selected == $id ? "selected='selected'" : " " ).' value="'.$id.'">'.$term->name.'</option>';
$args = "orderby=name&order=ASC&hide_empty=0&parent=".$id;
$sub_terms = get_terms( $taxo, $args );
foreach ( $sub_terms as $sub_term )
{
$sub_id = $sub_term->term_id;
$ret .= '<option '.($selected == $sub_id ? "selected='selected'" : " " ).' value="'.$sub_id.'"> | '.$sub_term->name.'</option>';
$args2 = "orderby=name&order=ASC&hide_empty=0&parent=".$sub_id;
$sub_terms2 = get_terms( $taxo, $args2 );
foreach ( $sub_terms2 as $sub_term2 )
{
$sub_id2 = $sub_term2->term_id;
$ret .= '<option '.($selected == $sub_id2 ? "selected='selected'" : " " ).' value="'.$sub_id2.'"> |
'.$sub_term2->name.'</option>';
}
}
}
$ret .= '</select>';
return $ret;
}
Here is another section of the code where the user interacts with that form
<li><h2><?php echo __('Category', 'ProjectTheme'); ?>:</h2>
<p><?php echo ProjectTheme_get_categories("project_cat",
!isset($_POST['project_cat_cat']) ? (is_array($cat) ? $cat[0]->term_id : "") : $_POST['project_cat_cat']
, __("Select Category","ProjectTheme"), "do_input"); ?></p>
</li>
Additional code that handles the submit function of the form
do_action('ProjectTheme_post_new_post_post',$pid);
if(isset($_POST['project_submit1']))
{
$project_title = trim($_POST['project_title']);
$project_description = nl2br($_POST['project_description']);
$project_category = $_POST['project_cat_cat'];
$project_location = trim($_POST['project_location_cat']);
$project_tags = trim($_POST['project_tags']);
$price = trim($_POST['price']);
$project_location_addr = trim($_POST['project_location_addr']);
$end = trim($_POST['ending']);
update_post_meta($pid, 'finalised_posted', '0');
//--------------------------------
$projectOK = 1;
if(empty($project_title)) { $projectOK = 0; $MYerror['title'] = __('You cannot leave the project title blank!','ProjectTheme'); }
if(empty($project_category)) { $projectOK = 0; $MYerror['cate'] = __('You cannot leave the project category blank!','ProjectTheme'); }
if(empty($project_description)) { $projectOK = 0; $MYerror['description'] = __('You cannot leave the project description blank!','ProjectTheme'); }
//--------------------------------
$project_category2 = $project_category;
$my_post = array();
$my_post['post_title'] = $project_title;
$my_post['post_status'] = 'draft';
$my_post['ID'] = $pid;
$my_post['post_content'] = $project_description;
$term = get_term( $project_category, 'project_cat' );
$project_category = $term->slug;
$term = get_term( $project_location, 'project_location' );
$project_location = $term->slug;
wp_update_post( $my_post );
wp_set_object_terms($pid, array($project_category),'project_cat');
wp_set_object_terms($pid, array($project_location),'project_location');
wp_set_post_tags( $pid, $project_tags);
Append a [] to Select Tag's name like this <select name="taxo_cat[]" multiple> and in your php code you can access array of values by calling $_POST['taxo_cat']
First of all, to be able to save all selected options, you must send them as an array. For this, the name of the element must be
name="'.$taxo.'_cat[]"
After, on the server side you'll find all selected values in the request variable.
I'm not familiar with Wordpress, but what has changed in your code is
$project_category = $_POST['project_cat_cat'];
$project_location = trim($_POST['project_location_cat']);`
project_category and project_location are now array and not strings, this means you must propably change the way the function get_term() is called, and
wp_set_object_terms($pid, array($project_category),'project_cat');
wp_set_object_terms($pid, array($project_location),'project_location');
has to be changed to
wp_set_object_terms($pid, $project_category,'project_cat');
wp_set_object_terms($pid, $project_location,'project_location');

Php Dynamic Menubar code error

I am having a problem with making the links in my bar work properly the database is setup like so my db http://bloodkittens.com/resources/upload/db.png
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
mysql_connect("localhost", "dbuser", "******");
mysql_select_db("guild");
// prepare special array with parent-child relations
$menuData = array(
'items' => array(),
'parents' => array()
);
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name FROM main_menu` ORDER BY parentID_menu");
while ($menuItem = mysql_fetch_assoc($result))
{
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}
// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData)
{
$html = '';
$parent='';
if (isset($menuData['parents'][$parentId]))
{
$menuClass= ($parentId==0) ? ' class="navbar" id="navbar"' : '';
$parent= ($parentId==0) ? 0 : 1;
$html = "<ul{$menuClass}>\n";
foreach ($menuData['parents'][$parentId] as $itemId)
{
//subment
$result=mysql_query("select * from main_menu where parentID_menu='$itemId'");
if (mysql_num_rows($result)>(int)0 && $parentId!=0) {
$subm =' class="navbar"';
}else{
$subm ='';
}
//end
$menu = $parentId == 0 ? ' class="menulink"' : ''; //class of main menu
$html .= '<li>' . "<a{$subm}{$menu} href=\"#\" >{$menuData['items'][$itemId]['name']}</a>";
// find childitems recursively
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
?>
How would i make it so that the value link_menu would be the href in the code for each separate entry in the db? rather then \'#\' because the code works completely and i'm very happy how it looks after i apply my css to it but the links aren't working
For work the menu sorting
must be add a new field in the table,
and change this query from
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name, link_menu link FROM main_menu ORDER BY parentID_menu");
to :
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name, link_menu link FROM main_menu ORDER BY menu_sort");
you never seem to select it
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu, link_menu, name FROM main_menu ORDER BY parentID_menu");
and then..
$html .= '<li>' . "<a{$subm}{$menu} href=\"{$menuData['items'][$itemId]['link_menu']}\" >{$menuData['items'][$itemId]['name']}</a>";
Instead of href=\"#\" >, use this:
href=\"{$menuData['items'][$itemId]['link_menu']}\" >
the code that i used was in the end like this i think i got it to work by pure luck but regardless i win : )
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
mysql_connect("localhost", "BloodKittens", "Zangoshi1");
mysql_select_db("bloodkittens");
// prepare special array with parent-child relations
$menuData = array(
'items' => array(),
'parents' => array(),
'links' => array()
);
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name, link_menu link FROM main_menu ORDER BY parentID_menu");
while ($menuItem = mysql_fetch_assoc($result))
{
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
$menuData['links'] = $menuItem['link'];
}
// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData)
{
$html = '';
$parent='';
if (isset($menuData['parents'][$parentId]))
{
$menuClass= ($parentId==0) ? ' class="navbar" id="navbar"' : '';
$parent= ($parentId==0) ? 0 : 1;
$html = "<ul{$menuClass}>\n";
foreach ($menuData['parents'][$parentId] as $itemId)
{
//subment
$result=mysql_query("select * from main_menu where parentID_menu='$itemId'");
if (mysql_num_rows($result)>(int)0 && $parentId!=0) {
$subm =' class="navbar"';
}else{
$subm ='';
}
//end
$menu = $parentId == 0 ? ' class="menulink"' : ''; //class of main menu
$html .= '<li>' . "<a{$subm}{$menu} href=\"{$menuData['items'][$itemId]['link']}\" >{$menuData['items'][$itemId]['name']}</a>";
// find childitems recursively
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
?>

Categories