Beautiful horizontal menu in php and mysql. §2

In this article, I will show you how to create multilevel menu in PHP and MySQL. Of course, you can come up with many options for creating it, but judging by the number of your questions on this topic, you need an example. And I will present it in this article. I note right away that this article makes sense only for those who know PHP and is able to work with MySQL. Everyone else needs to go through this one first, or read some books on PHP and MySQL.

First, let's create a table in the database with the following fields:

  • id- unique identificator.
  • title- Anchor links in the menu.
  • link- the address to which the menu item will lead.
  • parent_id- parent ID. If there is no parent item, then it will be NULL (or you can put another 0).

We figured out the table, now it's time php code. Full PHP code given below:

$mysqli = new mysqli("localhost", "root", "", "db"); // Connect to the database
$result_set = $mysqli->query("SELECT * FROM `menu`"); // Make a selection of all records from the table with the menu
$items = array(); // Array for menu items
while (($row = $result_set->fetch_assoc()) != false) $items[$row["id"]] = $row; // Fill the array with a selection from the database
$children = array(); // Array for matching child elements to their parent
foreach ($items as $item) (
if ($item["parent_id"]) $childrens[$item["id"]] = $item["parent_id"]; // Fill in the array
}
function printItem($item, $items, $children) (
/* Display the menu item */
echo "

  • ";
    echo "".$item["title"]."";
    $ul = false; // Were child elements displayed?
    while (true)(
    /* Endless loop where we search for all child elements */
    $key = array_search($item["id"], $children); // Looking for a child element
    if (!$key) (
    /* No child elements found */
    if ($ul) echo ""; // If child elements were displayed, then close the list
    break; // Exit the loop
    }
    unset($children[$key]); // Remove the found element (so that it is not displayed again)
    if (!$ul) (
    echo "
      "; // Start the inner list if there were no children yet
      $ul = true; // Set the flag
      }
      echo printItem($items[$key], $items, $children); // Recursively output all child elements
      }
      echo "";
      }
      ?>

      This code is fully working, however, you should understand that no one writes like this (in particular, output through echo HTML tags). And your task is to take the algorithm from this code, but not the code itself. And then connect this algorithm to your engine. I have tried to carefully comment the output code multilevel menu in PHP and MySQL, but, of course, it is not the most transparent and requires quite good initial knowledge. If you still don't know PHP and MySQL, then first I strongly recommend going through 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 the internal pages of the site themselves. A dynamically generated menu is very convenient, because it can be inserted anywhere on the site and, most importantly, at the right time. That is, when moving to different sections and subsections, you can dynamically expand and different blocks menu. 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 given script to 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 must also create a small script with settings that will store full address site, the path to the folders of the pages and meta descriptions of the site, the path to the files of the site menu 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 a 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 Right place 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 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 will appear in the future. 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

      Because it exposes the contents of the menu.php module. Below will be presented own development menu in PHP, which was written from scratch in 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 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's 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, 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

    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 a 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:

    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.

    ]]> ]]>

    Internet