Hardware and software setup

§2. How to make a vertical drop down menu in php

Because it exposes the contents of the menu.php module. Below is my own menu development in PHP, which was written from scratch in a notepad.

This code will be especially useful for dynamic sites that have self-written engines. I will offer two versions of the code that have minor differences (which difference will be explained later).

To begin with, I will give an approximate structure of the site for which this menu is suitable. The site structure should look like this (classic view):

/index.html /section_1/ /razdel_1/articles_1.html /razdel_1/articles_2.html ... /razdel_2/ /razdel_2/articles_1.html /razdel_2/articles_2.html ... ... ... /razdel_N/articles_2 .html

The site may also contain subsections for sections:

/section_1/podzaderl_1/ /section_1/podzaderl_1/articles_1.html /section_1/podzaderl_1/articles_2.html ... /section_1/podzaderl_2/articles_1.html /section_1/podzaderl_2/articles_2.html

This structure will also work for our menu with only minor differences.

I suggest creating a separate file for the menu in php. For example, menu.php would be a great name for such a file. To implement the menu, CSS menu styling is also introduced to make it more or less beautiful right away. Naturally, this style is given for reference only, since the designs of the sites are very different.

CSS menu style code:

.menu ( height:42px; padding:0 0 0 16px; background:url(images/spacer.png) repeat; ) .menu li ( display:block; float:left; ) .menu li.active ( background: #000011 ; ) .menu a ( color:#FFF; display:block; line-height:42px; text-decoration:none; padding:0 14px; ) .menu a:hover ( background:url(images/spacer.png) repeat ; )

Now, let's take a look at the first menu implementation in PHP, which is a bit of a simplification.

The first version of the menu code in PHP

\n"; for ($i=0;$i ": "
  • "; echo " ".$array_menu[$i]["name"]."
  • \n"; ) echo ""; ?>

    The menu can be divided into two parts. The first one contains an information array $array_menu , which contains the names of our sections with links to sections. Is there a way to add this data to the database? mySQL data, but there is no particular point in this, since the sample is very small, so this will not affect the speed of work.

    The second part contains the menu output via for loop. The loop compares the website address with the address from the $array_menu array. If there is a match, then we display the next section of the menu with a special class active:

  • , otherwise just
  • . This allows us to highlight with some color that part of the menu in which the user is located. In my opinion, this is a necessary thing for any site so that the user can understand which section he is in.

    The order in the array will be preserved when displaying the menu on the site. That is, the array must be filled in the order in which you want to display the menu.

    Note:
    In case the URLs (addresses) of the sections heading look like:
    /section_1
    or such
    /section_1/name_razdela.html
    then in array_menu you need to write the exact match:
    $array_menu[$i]["url"]="/section_1"
    or for the second case:
    $array_menu[$i]["url"]="/section_1/nazvanie_razdela.html";

    How does the first menu option work?
    It only highlights the menu if you are at the section heading address. For example, if the page address is /section_1/articles_1.html , then the menu will not be highlighted in any way.

    The second version of the code is a modified version of the first one and provides for the possibility of highlighting the menu even in articles that are in sections.

    The second version of the menu code in PHP

    "; for ($i=0;$i ": "
  • "; echo "".$array_menu[$i]["title"]."
  • "; ) else ( echo ($URL) == ($array_menu[$i]["url"]) ? "
  • ": "
  • "; echo "".$array_menu[$i]["title"]."
  • "; ) ) echo ""; ?>

    Not a single site is complete without navigation, or as the "site menu" is also called. So the site menu can be single-level and multi-level in the form of a tree. If there are no particular difficulties in terms of implementation with a single-level menu, then when creating a multi-level menu, you need to think carefully.

    The most important thing in this task is to design a database for our multi-level menu. Let's create a Categories table with three fields id, title, parent where:

    • ID- identifier
    • Title- Menu name
    • parent- Default category parent 0

    The field is responsible for branching the menu parent if parent = 0, then this category is the parent category. In order to add children to the parent category, you need to specify in the parent field ID the desired parent. For example:

    Tables with categories

    As can be seen from the table, the parent category Cars there are two descendants Mazda And Honda related by field parent. And the category Motorcycles two offspring are kawasaki And harley. At the same time, the category Boats has no descendants. I hope you understand how to link categories.

    Next, we move from words to practice. Let's create the Categories table.

    CREATE TABLE IF NOT EXISTS `categories` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `parent` int(10) unsigned NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ; -- -- Dump `categories` table data -- INSERT INTO `categories` (`id`, `title`, `parent`) VALUES (1, "Cars", 0), (2, "Motorcycles", 0) , (3, Mazda, 1), (4, Honda, 1), (5, Kawasaki, 2), (6, Harley, 2), (7, Mazda 3, 3 ), (8, "Mazda 6", 3), (9, "Sedan", 7), (10, "Hatchback", 7), (11, "Boats", 0), (12, "Liftback", 8), (13, "Crossover", 8), (14, "White", 13), (15, "Red", 13), (16, "Black", 13), (17, "Green", 13), (18, Mazda CX, 3), (19, Mazda MX, 3);

    The algorithm of work consists of the following:

    Creating a database connection

    query("SET NAMES "utf8""); /* * This is the "official" object-oriented way to do this * however $connect_error didn't work until PHP 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) ( die("Connection failed (" . $mysqli->connect_errno . ") " . $mysqli->connect_error); ) /* * If you want to be sure about compatibility with versions prior to 5.2 .9, * better code like this */ if (mysqli_connect_error()) ( die("Connection failed (" . mysqli_connect_errno() . ") " . mysqli_connect_error()); )

    Writing a function to get data from the Categories table

    //Get our menu array from the database as an array function getCat($mysqli)( $sql = "SELECT * FROM `categories`"; $res = $mysqli->query($sql); //Create an array where the array key is the menu ID $cat = array(); while($row = $res->fetch_assoc())( $cat[$row["id"]] = $row; ) return $cat; )

    We get an array like this, where the array key is the category ID.

    Array Tree Function by Tommy Lacroix

    //The function to build a tree from an array from Tommy Lacroix function getTree($dataset) ( $tree = array(); foreach ($dataset as $id => &$node) ( //If there are no attachments if (!$node[" parent"])( $tree[$id] = &$node; )else( //If there are children, then loop through the array $dataset[$node["parent"]]["childs"][$id] = &$ node; ) ) return $tree; )

    Getting an array in the form of a tree

    Whole script

    query("SET NAMES "utf8""); /* * This is the "official" object-oriented way to do this * however $connect_error didn't work until PHP 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) ( die("Connection failed (" . $mysqli->connect_errno . ") " . $mysqli->connect_error); ) /* * If you want to be sure about compatibility with versions prior to 5.2 .9, * it is better to use this code */ if (mysqli_connect_error()) ( die("Connection error (" . mysqli_connect_errno() . ") " . mysqli_connect_error()); ) //Get our menu array from the database as an array function getCat($mysqli)( $sql = "SELECT * FROM `categories`"; $res = $mysqli->query($sql); //Create an array where the array key is the menu ID $cat = array(); while ($row = $res->fetch_assoc())( $cat[$row["id"]] = $row; ) return $cat; ) //Function to build a tree from an array by Tommy Lacroix function getTree($dataset) ( $tree = array(); foreach ($dataset as $id => &$node) ( //If there are no attachments if (!$node["parent"])( $tree[$id] = &$node; )else( //If there are children, then iterate through the array $dataset[$node["parent"]]["childs"][$id] = &$node; ) ) return $tree; ) //Get prepared th array with data $cat = getCat($mysqli); //Create a tree menu $tree = getTree($cat); //Template for displaying the menu in the form of a tree function tplMenu($category)( $menu = "
  • ".$category["title"].""; if(isset($category["childs"]))( $menu .= "
      ".showCat($category["children"]) ."
    "; ) $menu .= "
  • "; return $menu; ) /** * Read our template recursively **/ function showCat($data)( $string = ""; foreach($data as $item)( $string .= tplMenu($item); ) return $string; ) //Get HTML markup $cat_menu = showCat($tree); //Display echo "
      ". $cat_menu ."
    "; ?>

    The result of the work

    Multilevel menu in PHP + MySQL for admin

    If you want to use this menu in the admin panel of your site, then you need to rewrite a couple of functions tplMenu(), showCat().

    ".$category["title"].""; )else( $menu = " "; ) if(isset($category["childs"]))( $i = 1; for($j = 0; $j< $i; $j++){ $str .= "→"; } $i++; $menu .= showCat($category["childs"], $str); } return $menu; } /** * Рекурсивно считываем наш шаблон **/ function showCat($data, $str){ $string = ""; $str = $str; foreach($data as $item){ $string .= tplMenu($item, $str); } return $string; } //Получаем HTML разметку $cat_menu = showCat($tree, ""); //Выводим на экран echo ""; ?>

    The result of the work

    Select Cars → Mazda →→ Mazda 3 →→→ Sedan →→→ Hatchback →→ Mazda 6 →→→ Liftback →→→ Crossover →→→→ White →→→→ Red →→→→ Black →→→→ Green →→ Mazda CX →→ Mazda MX → Honda Motorcycles → Kawasaki → Harley Boats

    In general, the task of creating a menu includes:

    • selection of HTML elements for building menus;
    • creating a menu template (creating a component template Menu);
    • enabling the menu display function (calling the component Menu) in a common pattern ("prologue" and "epilogue");
    • filling the menu in accordance with the structure of the site.

    Menu structure

    Any menu on the site is built on the basis of two components:

    • the $aMenuLinks data array, which defines the composition of the menu, sets the names and links for all menu items. The data array is managed through the administrative interface;
    • menu external presentation template. A menu template is a PHP code that defines appearance menu (component template Menu). The menu template processes an array of data, producing HTML code as output.

    Menu Data Array

    The data for each menu type is stored in a separate file whose name has the following format: .<тип меню>.menu.php. For example, to store menu data like left file will be used .left.menu.php, and to store data menu type top- file .top.menu.php.

    The menu is hierarchically inherited. Menu files are located in the folders of those sections of the site where the display of the corresponding menu types is required. If for this section the corresponding menu file has not been created, the system searches for the file in the directory one level higher.

    For example, because main menu (in the demo version of the product, this is a menu like top) should be displayed in all sections, then the file this menu placed only in the root directory of the site.

    Accordingly, the second level menu (in the demo version of the product, this menu left) is displayed separately for each section of the site. Therefore, in the folder of each section, a separate file is created for of this type menu.

    Another example: The visitor is in the /en/company/about/ section. To display a menu of type left, the menu file is searched by the system in the following sequence:

    1. /en/company/about/.left.menu.php
    2. /en/company/.left.menu.php
    3. /en/.left.menu.php
    4. /.left.menu.php

    If a menu is found in one of the directories, then the search stops and it is no longer searched in subsequent directories.

    The Bitrix Framework system also allows you to create menu dynamic type To do this, in the Menu component, enable the option Include files with names like.menu_type.menu_ext.php("USE_EXT" => "Y"), which is disabled by default.. Those. the data array of such menus is automatically generated based on some data obtained using the program code. This code should be stored in the folder of the corresponding section of the site in a file named .<тип меню>.menu_ext.php.

    The main task of such files is to manipulate the $aMenuLinks array. These files are not edited visually in the module Structure management, so they can't be accidentally edited when visually editing the menu. When creating this file, use the component Menu items (bitrix:menu.sections).

    Note: In the paragraph above, we are only talking about supplementing the created menu with the names of sections of infoblocks. For example, this option is not suitable for supplementing the menu with the names of the forums.

    Attention! If non-NC catalog partitions are used as menu items, variables must be specified in meaningful query variables.

    An example of such a menu is left menu section Book catalog presented in the demo version of the product. Here are the first two menu items The authors And Reviews created in the usual way, and the rest ( business literature, Children's literature etc.) are formed dynamically.

    In this case, the names of the catalog groups are used as menu items. Books, created on the basis of information blocks. Program code, on the basis of which the menu is generated, is stored in the file .left.menu_ext.php in the /e-store/books/ folder.


    In files .<тип меню>.menu.php the following standard variables can be used:

    • $sMenuTemplate - absolute path to the menu template (this variable is rarely used);
    • $aMenuLinks - an array, each element of which describes the next menu item.

      The structure of this array:

      Array ( => menu item 1 Array ( => menu item title => link to the menu item => array of additional links to highlight the menu item: Array ( => link 1 => link 2 ...) => array of additional variables passed to the menu template: Array ([variable name 1] => variable value 1 [variable name 2] => variable value 2 ...) => the condition under which the menu item appears is a PHP expression that should return "true") => menu item 2 => menu item 3 ...)

    Menu File Examples

    IsAuthorized()"), Array("Learning Book", "gradebook.php", Array(), Array(), "\$GLOBALS["USER"]->IsAuthorized()"), Array("Specialist Questionnaire" , "profile.php", Array(), Array(), "\$GLOBALS["USER"]->IsAuthorized()")), ?>IncludeComponent("bitrix:menu.sections", "", Array("ID" => $_REQUEST["ELEMENT_ID"], "IBLOCK_TYPE" => "books", "IBLOCK_ID" => "30", "SECTION_URL" = > "/e-store/books/index.php?SECTION_ID=#ID#", "CACHE_TIME" => "3600")); $aMenuLinks = array_merge($aMenuLinks, $aMenuLinksExt); ?>

    Organization of the menu display

    The display of the menu on the pages of the site is performed using the component Menu (bitrix:menu). For example, calling the top menu on a demo site looks like this.

    The menu of a site in php, which is controlled by php scripts, has its own characteristics. These are not just absolute or relative links, although this may well be the case, but, as a rule, dynamically generated sidebar link blocks with sections and subsections and link blocks from themselves internal pages site. A dynamically generated menu is very convenient, because it can be inserted anywhere on the site and, most importantly, in right time. That is, when you go to different sections and subsections, you can dynamically expand different menu blocks. Moreover, they can be different not only in content, but also in form and design. In a static site, it is also quite possible to do such feints, but it will cost additional files templates and a lot of other tricks. While a site written in php does not require any of this. The template will remain as it was. Everything will be controlled by one or more simple php scripts.

    In order to verify this, it is enough to write a php script to dynamically generate a menu, for example, the first heading and force it to expand the menu of this heading through the previously written script. The rest of the rubrics can be formed in a similar way. Moreover, the code of the script itself will not change much. Only the text file will change, which will define the names of the links and the links themselves. The code for such a script is given below.

    // Menu builder
    $menu = @file($rubric1_menu);
    $lines = count($menu);
    for ($i = 0; $i< $lines; $i++)
    {
    list($menu_link,$menu_name,$menu_title)=explode("::", $menu[$i]);
    if($page == rub1_part1 and $i == 0) ($refcolor = "style="color:#cc0000"";)
    elseif($page == rub1_part2 and $i == 1) ($refcolor = "style="color:#cc0000"";)
    elseif($page == rub1_part3 and $i == 2) ($refcolor = "style="color:#cc0000"";)
    else ($refcolor = "";)
    $rubric1.="

  • ".$menu_name."
  • ";
    }
    ?>

    In order for such a script to work, a text file is needed in which the names of the menu links, the links themselves and their title will be stored. It is not difficult to create such a file, it is enough to execute the File -> New command from the Dreamweaver main menu, create a new html document, as described earlier, check and, if necessary, change the encoding of the new file to UTF-8, and then save it under the name rubric1.dat in the data folder previously created for it. The full path to this file will be D:/Mysitephp/data/rubric1.dat. The contents of the file below are the links themselves, their names and their titles (tips). In addition, in order to run this script into work, it must be connected using the function include() in the main.php template engine.

    Rub1_part1::Section 1::Section 1 of rubric 1::
    rub1_part2::Section 2::Section 2 rubric 1::
    rub1_part3::Section 3::Section 3 rubric 1::

    In addition, you also need to create a small script with settings that will store the full address of the site, the paths to the folders of the pages and meta descriptions of the site, the paths to the site menu files and connect it using the function include() in the main.php template engine. To do this, you need to create a new php file, and save it under a name such as settings.php in the php folder. The full path to the file will be D:/Mysitephp/php/setings.php and its content is shown below.

    # folder with html documents
    $doctemplates = "templates";
    # full path to script directory
    $turl="http://mysitephp.ru";
    # database with data
    $rubric1_menu = "data/rubric1.dat";
    ?>

    How does the php script for menu generation work? First to the $menu variable using the function file() the content of the text file rubric1.dat is placed. Then the function count() counts the number of lines in text file and functions list() And explode() in the cycle, the menu itself is unfolded, where by the method of gluing lines (dot operation . ) strings of links with their names and titles are formed, which is then placed in the $rubric1 variable. Next, the templating script, where the menu script is connected by the function include(), moves the contents of the $rubric1 variable to the right place on the site using the previously described function repl().

    Such a menu will not work yet, since it contains only the links themselves with all the necessary attributes, but there is no script that would ensure the transition to these links and the opening of the site pages that will correspond to these links. This php script we'll take it further.

    Further it is possible the project updated by a script of formation of the menu. You can also download the updated project on the page that will open after registration and activation of the free subscription on the panel on the right. The page address must be saved. It is on this page that links to download project updates, various useful scripts, programs, lessons and video tutorials on circuitry, programming and site building for newbies.

    The downloaded site php project updated with new scripts can now be compared with what happened as a result of the above actions. Further, in order to eliminate discrepancies, it will be useful to completely replace the project with the downloaded one, perform the operation, start the Denwer server, type mysitephp.ru in the browser window and see what came of it. In the upper left part of the template, the menu of the first section should expand, as shown in the picture below.

    Go and melt in your favorite social network

    If you are interested in the answer to the question of how to create a website menu, then you have come to the right place.

    We will look at creating a dynamic menu in php, written specifically for dummies in programming, as well as for those who are still in the tank.

    Lesson 3

    Let's create the future layout of our site. To do this, draw a super beautiful website in Photoshop and cut it into pieces. Imagine that the header, logo, menu and footer are not written in words, as in this example, and these are exquisitely and colorfully designed elements of the site.

    For example, let's create three pages and call them Section 1, Section 2, Section 3

    This text is for different pages will be different, but we will not bother with it and leave it as it is on all pages.

    Let's start creating a website in php.

    1. Separate the header, logo, menu, footer blocks into separate files with the php or html extension

    header.html

    logo.html

    menu.html

    footer.html

    Let's add a file with this text to see it on all pages. Let's call it text.html

    Note. From now on, I will keep further records directly in the file text.html

    2. Let's create a template for our site in php.

    To do this, let's do it simply - save the real file, but with the php extension and erase all the text content. Let it not be professional, but it is understandable, and we will complicate everything later. Now the main thing is to understand the principle of layout.

    3. Now we don't need the template.html file.

    Thanks to him, we have an idea of ​​​​how our site will look like.

    4. Our template is the template.php file

    We will now insert all the elements of the site into it using the include command.

    5. Let's create three pages, as we originally intended.

    Section 1, let's call 1.php

    Section 2, let's call 2.php

    Section 3, let's call 3.php

    To do this, you can use the simplest command save as...

    For the smallest I will explain: open the file template.php, then press save as... and save under the name 1.php, repeat the procedure and sequentially save the pages of the site 2.php, 3.php

    We got 3 pages with the same design. It is enough to insert instead of a file text.html another, supplement with different pictures or any html codes, scripts and the content of each page will be unique.

    Attention!

    If the file is not created index.php for the main page, then in the browser, by typing the site address, we will not see the site itself, but only the directory structure (list of folders).

    You can look in Denver and see for yourself. Let's fix the situation - create a file index.php and call for a long time without further ado home. Let's create a file text-home.html and with the command include paste on the newly created home page site.

    6. How to view a site in php?

    What happened - so just do not see. This is no longer a template with an html extension.

    But not a problem either. We need our own, i.e. local server on the computer. To do this, we will install Denver and we will look at the result of our work in the browser without going online.

    Now here is the order. I typed in the site address and saw everything that had just been created in a normal form with a design.

    Now let's take on the php site menu.

    1. Open the menu.html file and turn sections 1, 2 and 3 into site links. Links in php are created in different ways.

    Our task is to learn how to feel the site created in php. Therefore, we will make links, as on a regular static site Section 1, etc.

    I really like this link creation procedure in Macromedia Dreamweaver. Have time to reap OK and drink coffee.

    2. How to make the link in the menu inactive if the visitor is on this page.

    It will be more convenient for the visitor to navigate the site knowing which page he is on.

    If you have completed all the steps strictly point by point, then you can see that all the links in the menu are constantly active with us. How to fix it?

    Let's start with the definition of what is Conditional statements

    - this is when some action is performed or not performed depending on the conditions.

    Let's do the following:

    • We will need variables and one conditional operator:

    if ($master == "Master")// this condition. If it is executed, then in this place of the menu, using the echo command, ordinary HTML tags are inserted that display the inscription "Home".

    echo "

    home

    ";

    else//means "otherwise" - what happens if the condition is not met. In this case, if the condition is not met, the inscription "Main" will be a link leading to the main page.

    echo "

    home

    ";

    • We have come up with a condition, but in order to check variableyou need to ask it.

    To do this, place the following code blocks on all pages:

    $master ="Master";

    $master ="Section 1";

    $master ="Section 2";

    $master ="Section 3";

    As you can see, each page has its own code.

    So, our practical steps for creating a php menu will be as follows:

    1) Opening the file index.php

    and paste the code

    $master ="Master";

    to the insertion point of the code that displays the site menu itself include "menu.html";
    ?>

    2) Opening the file menu.html and insert the code with the condition instead of a simple html link to the main page.

    We look in the browser and admire! If we go to the main page, the link is no longer active!

    3) Repeat steps 1 and 2 with pages 1.php, 2.php, 3.php

    Repetition 1:

    1) Open the 1.php file and paste before the code that displays the menu a block with a given variable

    $master ="Section 1";

    2) Open the menu.html file and paste the code with the condition instead of a simple link Section 1 by making the following changes:

    if ($master == "Section 1")// this condition. If it is executed, then in this place of the menu, using the echo command, ordinary HTML tags are inserted that display the inscription "Section 1".

    echo "

    Section 1

    ";

    else//means "otherwise" - what happens if the condition is not met. In this case, if the condition is not met, the inscription "Section 1" will be a link leading to the main page.

    echo "

    Section 1

    ";

    The miracle happened again! Now if we are on the page Section 1, the link in the menu is not active.

    Repetition is the mother of learning! Or for those in the tank! Again

    repetition 2

    1) Open file 2.php and paste the code.

    $master ="Section 2";

    2) Open the menu.html file again and paste the code with the condition

    if ($master == "Section 2")// this condition. If it is executed, then in this place of the menu, using the echo command, ordinary HTML tags are inserted that display the inscription "Section 2".

    echo "

    Section 2

    ";

    else//means "otherwise" - what happens if the condition is not met. In this case, if the condition is not met, the inscription "Section 2" will be a link leading to the main page.

    echo "

    Section 2

    ";

    Repetition 3

    1) We open file 3.php and set the variable.

    $master ="Section 3";

    2) In the menu.html file, insert the code with the condition instead of the link Section 3, the changes are:

    if ($master == "Section 3")// this condition. If it is executed, then in this place of the menu, using the echo command, ordinary HTML tags are inserted that display the inscription "Section 3".

    echo "

    Section 3

    ";

    else//means "otherwise" - what happens if the condition is not met. In this case, if the condition is not met, the inscription "Section 3" will be a link leading to the main page.

    echo "

    Section 3

    ";

    Outcome: we instead of links in the menu of this kind

    home


    Section 1

    Section 2


    Section 3

    This php tutorial was written by popular demand from site visitors and is a practical guide to learning how to create a dynamic menu for a php site.

    The following webmaster's cheat sheet will tell you how to make unique titles, descriptions and keywords for each page in php.

    You can download the archive with all site template and php menu files. Recommended for beginners in programming.

    If you are ready for a serious study of php, then it is difficult to find a better video course from Popov. He has a lot of experience and a good style.

    ]]> ]]>

    Liked the article? Share with friends!
    Was this article helpful?
    Yes
    Not
    Thanks for your feedback!
    Something went wrong and your vote was not counted.
    Thanks. Your message has been sent
    Did you find an error in the text?
    Select it, click Ctrl+Enter and we'll fix it!