Bagatorіvneve menu in PHP and MySQL. §2. How to create a drop down vertical menu in php Inurl php own menu id pyramid

Golovna / Nalashtuvannya

If your website doesn't have a single web page, consider adding a navigation bar (menu). Menu - distributed to the website, which helps to navigate the site. Be it a menu or a list of messages that should be kept on the internal side of the site. Himself in a simple way add a navigation panel to the site and create a menu help CSS and HTML.

Vertical Menu

The first step in creating a vertical menu will be creating a bulleted list. We also need the ability to identify the list, so we added the id attribute with the "navbar" identifier. Leather element

  • our list of revenge for one request:

    Our next task is to drop off styles from the list, installed behind the locks. We need to clean up the names and internal entries of the list itself and the markers near the items in the list. Let's set the required width:

    #navbar ( margin: 0; padding: 0; list-style-type: none; width: 100px; )

    Now the time has come to style yourself. We add the background color to them, change the parameters of the text: color, size and size of the font, lightly reinforce, add small steps and change the size of the font element from row to block. Dodatkovo was added to the left and bottom frames to the items in the list.

    The most important part of our changes is the redistribution of small elements on blocks. Now our messages occupy the entire available space of the item in the list, so to switch to the message, we no longer need to point the cursor exactly at the text.

    #navbar a ( background-color: #949494; color: #fff; padding: 5px; text-decoration: none; font-weight: bold; border-left: 5px solid #33ADFF; display: block; ) #navbar li ( border-left: 10px solid #666; border-bottom: 1px solid #666;

    We have combined all the code, more descriptions, into one butt, now, by pressing the try button, you can go to the side with the butt and see the result:

    naming the document

    try

    When hovering the mouse cursor over a menu item old look you can change, turning the respect of the coristuvach. You can create such an effect by helping the pseudo-class: hover.

    Let's turn to the butt of the vertical menu that we looked at earlier and add to the style table, the next rule:

    #navbar a:hover ( background-color: #666; border-left: 5px solid #3333FF; ) Try »

    Horizontal Menu

    At the front butt, we looked at the vertical navigation panel, which is most likely to be used on the sites of left-handed or right-handed in the main content area. However, menus with navigational messages are also often displayed horizontally at the top of the web page.

    Horizontal menu can be created for additional stylization of the great list. Power display for elements

  • it is necessary to set the values ​​inline, so that the items in the list are sorted one by one.

    To place menu items horizontally on the back, we create a marking list with messages:

    Let's write a couple of rules for our list, what to throw off the style, what to win for the lists for locks, and revisit the list from the block on the row:

    #navbar ( margin: 0; padding: 0; list-style-type: none; ) #navbar li ( display: inline; ) Try »

    Now we have lost more than stylish design for our horizontal menu:

    #navbar ( margin: 0; padding: 0; list-style-type: none; border: 2px solid #0066FF; border-radius: 20px 5px; width: 550px; text-align: center; background-color: #33ADFF; ) #navbar a ( color: #fff; padding: 5px 10px; text-decoration: none; font-weight: bold; display: inline-block; width: 100px; ) #navbar a:hover ( border-radius: 20px 5px ; background-color: #0066FF; ) Try »

    VIP menu

    The menu, as we will create, mother of the main navigational messages, sorted in the horizontal navigation bar, and sub-items, as soon as the mouse cursor hovered over that menu item, until a certain number of sub-items are visible.

    First, we need to create the HTML structure of our menu. The main navigational messages we can add to the marked list:

    Subitem mi rozmіstimo in an okremy list, putting yogo in the element

  • , in order to avenge the father’s request for sub-points. Now we can read the structure of our future navigation panel:

    try

    Now let's get down to writing the CSS code. For the cob it is necessary to attach a list with sub-items for additional information display: none; so that the stench didn't show up on the web site for the whole hour. For displaying subpoints, we need, so when hovering over an element

  • the list of new transformations on the block element:

    #navbar ul ( display: none; ) #navbar li:hover ul ( display: block; )

    We take in both lists and the markers inserted behind the lock. Elements of the list with navigation aids robably floating, shaping horizontal menu, but for the elements of the list, which should be checked subitems, set float: none; , so that the stench seemed to be one under one.

    #navbar, #navbar ul ( margin: 0; padding: 0; list-style-type: none; ) #navbar li ( float: left; ) #navbar ul li ( float: none; )

    Then we need to work in such a way that our submenu, which does not fall out, does not interfere with the content, pushing it under the navigation panel, down. For which we put an item to the list position: relative; and to the list, what to revenge subpoints position: absolute; and to add the power of the top to the values ​​of 100%, so that the position of the sub-menu would be exactly according to the forces.

    #navbar ul ( display: none; position: absolute; top: 100%; ) #navbar li ( float: left; position: relative; ) #navbar ( height: 30px; ) Try »

    The height for the Batkiv list was added specially, so that browsers do not check for floating content in the element, without adding the height, our list will be ignored by the browser and content that follows the list will wrap around our menu.

    Now we have lost the style of insulting our lists and menus, what you see, be ready:

    #navbar ul ( display: none; background-color: #f90; position: absolute; top: 100%; ) #navbar li:hover ul ( display: block; ) #navbar, #navbar ul ( margin: 0; padding: 0; list-style-type: none;) #navbar ( height: 30px; background-color: #666; padding-left: 25px; min-width: 470px; height: 100%; ) #navbar li a ( display: block; padding: 6px; width: 100px; color: #fff; text-decoration: none; ) #navbar li:hover ( background-color: #f90; ) #navbar ul li:hover ( background-color: #666; )

    Site menu in php, which is handled by php scripts, has its own peculiarities. It’s not just an absolute or a vodnosnі possilannya, although it can be done as a whole, but, as a rule, blocks of silan of side panels, which are dynamically molded with razdіla and poddrozdіla і blocks of silan from the very inner sides of the site. The menu, which is dynamically formed, is already handy, the way it can be inserted into the site, whether it be the place or the most important at the right time. So when you go to the different sections and sub-folders, you can dynamically expand the different menu blocks. Moreover, the stench can be different not only for the zmist, but for the shape and design. For a static site, you can still work with such tricks, but you will also be able to add additional files to the template and still be a lot of tricks. Wanting a site writing in php does not help anything. Lose the template, yak i buv. Usim keruvateme one or a few simple php scripts.

    In order to switch to another one, it is enough to write a php script for a dynamic menu formation, for example, the first heading and to change the menu of the heading through the previous script. Other headings can be formulated in a similar order. Moreover, the code of the script itself has little practical change. Change only a text file, which is meaningfully called the message and the message itself. The code of such a script is hovered below the text.

    // Shaping Menu
    $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 to process such a script in the required text file, in which case name the menu, send that title itself. To create such a file is clumsy, it is enough to convert the Dreamweaver main menu command File -> New, create a new html document, as described earlier, revise and change the coding of the new file to UTF-8, and then save it rubric1 .dat in front of my dad's data. The next path to this file will be D:/Mysitephp/data/rubric1.dat. Instead of the file, hovering below, if necessary, їх name and їх title (suggestions). Krim moreover, schob run Danish script for the robot, it is necessary to connect it for additional functions include() at the template engine main.php.

    Rub1_part1::Part 1::Part 1 rubric 1::
    rub1_part2::Part 2::Part 2 rubrics 1::
    rub1_part3::Part 3::Part 3 rubrics 1::

    In addition, it is also necessary to create a small script with settings, in which the addresses of the site are saved, paths to the folders of the sides and meta descriptions of the site, paths to the files in the menu of the site and connect yoga for additional functions include() at the template engine main.php. For whom it is necessary to create new php file, and save it for me, for example, setings.php in the php folder. The next path to the file will be D:/Mysitephp/php/setings.php, and it will be hovered below.

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

    How do you use a php script to form a menu? Back to change $menu for additional functions file() Move to the text file rubric1.dat. Potim function count() increase the number of rows text file and functions list()і explode() at the cycle, the menu itself is opened, using the method of gluing rows (dot operation . ) are formed historically with their names and titles, so that we can move into the change of $rubric1. Dali the template engine script, where the menu script is enabled by the function include(), move instead of changing $rubric1 to the site for additional help already described previously functions repl().

    There will be no such menu for the time being, the shards in the new one are only sent by themselves with the necessary attributes, but not, the script, which will ensure the transition for these messages and the acknowledgment of the sides of the site, yak Cim php script we'll deal with.

    Dali can be a project of updates with a script for forming a menu. You can also request updates to the project on the side, as it is shown after the registration and activation of the free subscription on the right-hand panel. It is necessary to save the addresses of the party. On the other hand, we applied for the promotion of updating the project, various blue scripts, programs, lessons and video lessons from circuitry, programming and website development. for beginners.

    Requests for updates with new scripts from the php project to the site can now be compared with it, which happened as a result of the above descriptions. Then, in order to turn off the reading, I will replace the project for privatization again, start the operation, start the Denwer server, type mysitephp.ru in the browser window and take a look at what happened. At the left upper part of the template, the menu of the first section will open, as shown in the small picture below.

    Go and get along with your favorite socialist

    The site should not be complete without navigation, otherwise it is also called the "site menu". So the axis of the menu for the site is one-to-one and one-to-one at the same tree. Although there is no one-to-one menu of special folding options in the implementation plan, it is necessary to think carefully when creating a rich menu.

    The most important task of our task is to design a data base for our rich menu. Let's create a table Categories from three fields id, title, parent de:

    • ID- identifier
    • Title- Menu name
    • parent- Father of the category for zamovchuvannyam 0

    For the layout of the menu parent yakscho parent = 0, then this category is Batkivskaya. In order to add names to the father's category, it is necessary to indicate in the parent field ID necessary father. For example:

    Tables with categories

    As can be seen from the tables, in the Batkiv category Carsє two nashashki - tse Mazdaі Honda pov'yazanih across the field parent. And the category Motorcycles two bait - tse Kawasakiі harley. With this, the Chovna category does not have awards. I am sure that you have figured out how to rank the categories.

    Let's move on to practice. Let's create a category 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, "Chovni", 0), (12, "Liftback", 8), (13, "Crossover", 8), (14, "Biliy", 13), (15, "Chervoniy", 13), (16, "Black", 13), (17, "Green", 13), (18, Mazda CX, 3), (19, Mazda MX, 3);

    The robotic algorithm is composed of the offensive:

    We create a connection with the data base

    query("SET NAMES "utf8""); /* * The "official" object-orientation method for generating * the $connect_error prote does not work up to PHP versions 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) ( die("Connection pardon (" . $mysqli->connect_errno . ") " . $mysqli->connect_error); ) /* * This should be added to connect before 5.2 .9, * better twist code like this */ if (mysqli_connect_error()) ( die("Connection pardon (" . mysqli_connect_errno() . ") " . mysqli_connect_error()); )

    We write the function of extracting data from tables.

    //Remove the array of our menu from the database in the form of an array function getCat($mysqli)( $sql = "SELECT * FROM `categories`"; $res = $mysqli->query($sql); //Create an array de key array є Menu ID $cat = array(); while($row = $res->fetch_assoc())( $cat[$row["id"]] $ $row;

    We take an array of this kind, de keying the array with category IDs.

    Function to wake a tree from an array of views Tommy Lacroix

    //Function to get a tree from an array like Tommy Lacroix function getTree($dataset) ( $tree = array(); foreach ($dataset as $id => &$node) ( //There is no nest if (!$node[" parent"])( $tree[$id] = &$node; )else( //If there are headers, then iterate over the array $dataset[$node["parent"]]["childs"][$id] = &$ node; ) ) return $tree; )

    Take away the array from the looking tree

    Script as a whole

    query("SET NAMES "utf8""); /* * The "official" object-orientation method for generating * the $connect_error prote does not work up to PHP versions 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) ( die("Connection pardon (" . $mysqli->connect_errno . ") " . $mysqli->connect_error); ) /* * This should be added to connect before 5.2 .9, * better twist code like this */ if (mysqli_connect_error()) ( die("Connection pardon (" . mysqli_connect_errno() . ") " . mysqli_connect_error()); ) function getCat($mysqli)( $sql = "SELECT * FROM `categories`"; $res = $mysqli->query($sql); //Create array de key array є menu ID $cat = array(); while ($row = $res->fetch_assoc())( $cat[$row["id"]] = $row; ) return $cat; ) //Fetch tree from array like Tommy Lacroix function getTree($dataset) ( $tree = array(); foreach ($dataset as $id => &$node) ( //There is no nester if (!$node["parent"])( $tree[$id] = &$node; )else( //Because of the headers, then iterate over the array $dataset[$node["parent"]]["childs"][$id] = &$node; ) ) return $tree; ) //It is necessary to prepare the array from danimi $cat = getCat($mysqli); // Create a tree-like menu $ Tree = getTree($ Cat); //Template for displaying the menu in the tree view 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; ) //HTML layout required $cat_menu = showCat($tree); //Displayed on the screen echo "
      ". $cat_menu ."
    "; ?>

    Robot result

    Bagator_vneve menu in PHP + MySQL for admin

    If you want to win this menu in the administration 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 ""; ?>

    Robot result

    Select Cars → Mazda →→ Mazda 3 →→→ Sedan →→→ Hatchback →→ Mazda 6 →→→ Liftback →→→ Crossover →→→→ White →→→→ Chervoniy →→→→ Chorniy →→→→→ Zeleny → → Mazda CX →→ Mazda MX → Honda Motorcycles → Kawasaki → Harley Chovny

    Oskіlki won't open the menu.php module. Below you will find a detailed description of the menu in PHP, as the bula was written from scratch in a notepad.

    This code will be especially suitable for dynamic sites, as self-written engines can. I will propagate two variants of the code, as there may be ambiguous details (whose difference will be explained later).

    For the cob I will direct the structure of the site, for some kind of menu. The structure of the site is to blame for such a look ( classic look):

    /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 can be found in other distributions and updates:

    /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

    Such a structure is also practical for our menu, but with small dimensions.

    I'm proposing to create an okremium file for menus in PHP. For example, menu.php would be a magical name for such a file. For the implementation of the menu, the style of the CSS menu is also presented, so that it is more or less beautiful. Naturally, this style is given only for recognition, design shards from sites in a different way.

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

    Now, let's take a look at the first option for implementing a menu in PHP, which we can forgive a trifle.

    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 step is to remove the $array_menu information array, to which the names of our distributions will be entered from the distribution requests. Є variant danih mySQL Ale especially sensu in tsommu no, the shards of the viberka zovsіm is small, to that on the speed of the work it’s not a matter of course.

    Another part is to see the menu through the for loop. The cycle takes a consistent address of the site with the address of the $array_menu array. If it’s not, then we’ll display a black section of the menu with a special class active:

  • , otherwise just
  • . Tse allows us to see, as if in color, that part of the menu, where the koristuvach is known. In my opinion, it is necessary to be rich for any site, so that you can become knowledgeable in a moment, know which wines you have.

    The order of direct entry in the array will be saved when the menu is displayed on the website. Tobto the array needs to be put in order, for which it is necessary to bring up the menu.

    Note:
    How the URL (address) heading may look like:
    /section_1
    otherwise such
    /section_1/name_razdela.html
    then in array_menu you need to write the exact value:
    $array_menu[$i]["url"]="/section_1"
    or for another vipadu:
    $array_menu[$i]["url"]="/section_1/nazvanie_razdela.html";

    How do you make the first menu option?
    Vіn pіdsvіchuє menu less, if you know for the address of the distribution. For example, if the page address is /section_1/articles_1.html, then the menu will not be displayed.

    Another variant of the code is to modify the first variant and transfer the ability to switch the menu to the articles that are found in the distributions.

    Another option for 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 ""; ?>

    At this article, I will show you how you can create Different menus in PHP and MySQL. Insanely, options for this creation can be rich, but, judging by the number of your meals on this topic, you need an butt. I will bring the first yoga to my article. I’ll tell you right away what article might be sensible for you, who knows PHP and vmіє practice s MySQL. Everyone else needs to go through this, or read some books on PHP and MySQL.

    For the cob, we create a table in the database with advancing fields:

    • id- Unique identifier.
    • title- menu anchor.
    • link- addresses, on the yaku will lead the menu item.
    • parent_id- Batkiv ID. If there is no batkivsky item, then it will be NULL (otherwise you can put 0).

    We have sorted out the table, now the hour has come PHP code. Povniy PHP code hover below:

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

  • ";
    echo "".$item["title"]."";
    $ul = false; // Which child elements were produced?
    while (true)(
    /* Infinite loop, for which we are looking for all child elements */
    $key = array_search($item["id"], $children); // Shut down child element
    if (!$key) (
    /* No child elements found */
    if ($ul) echo "// If child elements were generated, then the list is closed
    break; // Seen from the loop
    }
    unset($children[$key]); // We can see the knowledge element (if the wine is not shown again)
    if (!$ul) (
    echo "
      // Repairing the internal list, since there were no child elements yet
      $ul=true; // Set ensign
      }
      echo printItem($items[$key], $items, $children); // Recursively display all child elements
      }
      echo "";
      }
      ?>

      This code is completely working, however, you are responsible for understanding that you don’t write anything like that (zokrema, visnovok through echo HTML tags). І Your task is to take the algorithm from this code, not the code itself. And then the algorithm is connected to your engine. I tried my best to comment the code to the output custom menu in PHP and MySQL, ale, insanely, vin is not a visionary and vimagaє already indecent cob knowledge. Yakshcho Vesche nasty know PHP and MySQL, then I recommend to go through cei

  • © 2022 androidas.ru - All about Android