Beautiful horizontal menu php mysql. §2. How to make a dropdown vertical menu in php. Writing the code for the menu

Apr 23 2017

In the previous lessons, we have discussed with examples what arrays are. In this tutorial, we will use arrays in practice to create a menu on a website.

How are they more convenient than regular HTML tags?

Well, let's say our site has 100 pages, each of which has the same menu. And suddenly we needed to change the menu items. Using only HTML, we will have to edit 100 pages of the site, which is a lot. So PHP comes to the rescue in such situations. It will be enough to change the menu items just once in one file.

Now let's go.

On local hosting in the folder “ domains create a folder called “ array- menu. local”.

We create four files in this folder: index. php, about. php, contact. php and menu. php.

!!! The syntax of the files should bePHP.

In the index.php file, we write a simple HTML wireframe.




charset = "utf-8">



home


include("menu.php");
?>

Let's copy this code to about.php and contact.php files. We change only the names of the pages in the tag

.

We write the code for the menu.

In file menu.php we write an associative array.

$ menu = array (
"index "=>" index.php ",
"about" => "about.php",
"contacts" => "contact.php"
);
?>

Below using HTML tags writing a menu.

In the browser, we will see a regular menu in the form of a list.

By clicking on any menu item, we will go to the corresponding page, the menu will be on all pages.

Now let's complicate the task. We delete everything from the file menu.php and...

We write a multidimensional array.




charset = "utf-8">
<span>Using an array to display the menu on the site.</span>


$ menu = array (
array("link" => "Home", "href" => "index.php"),
array("link" => "About us", "href" => "about.php"),
array("link" => "Contacts", "href" => "contact.php")
);
?>



And at the last stage ...

Rendering the menu using a loop foreach.

Remove the list from the menu.php file

    and write the following code instead.

    echo"

      " ;
      foreach($ menu as$ item) (
      echo "
    • ($ item)
    • " ;
      }

      We will see the same result in the browser.

      To change the menu items, it is enough to change them in the file menu.php just once.

      The php site menu, which is controlled by php scripts, has its own characteristics. These are not just absolute or relative links, although this may well be so, 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 switching 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 tricks, but it will cost additional template files and a lot of other tweaks. While a site written in php does not require anything of this. The template will remain as it was. Everything will be controlled by one or several simple php scripts.

      In order to be convinced of this, it is enough to write a php script for dynamically forming a menu, for example, the first heading and force it to expand the menu of this heading through a script already written earlier. The rest of the headings can be formed in a similar way. Moreover, the code of the script itself will hardly change much. Only the text file will change, which will determine the names of the links and the links themselves. The code for such a script is given below in the text.

      // 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, just execute the File -> New command from the main menu of Dreamweaver, 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 (hints). In addition, in order to run this script, it must be connected using the function include () in the main.php template engine.

      Rub1_part1 :: Section 1 :: Section 1 Headings 1 ::
      rub1_part2 :: Section 2 :: Section 2 Headings 1 ::
      rub1_part3 :: Section 3 :: Section 3 Headings 1 ::

      In addition, you must also create a small script with settings, which will store the full site address, paths to the page folders and meta descriptions of the site, 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 setings.php in the php folder. The full path to the file will be D: /Mysitephp/php/setings.php and its contents are shown below.

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

      How does the php script for creating a menu work? First into the $ menu variable using the function file () the contents of the text file rubric1.dat are placed. Then the function count () counts the number of lines in a text file and functions list () and explode () in the loop, the menu itself unfolds, where by gluing lines (operation dot . ) links lines with their names and titles are formed, which is then placed in the $ rubric1 variable. Next is the template engine script, where the menu script is connected by the function include (), moves the contents of the $ rubric1 variable to the desired 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 no script that would ensure the transition to these links and the opening of the site pages that will correspond to these links. We will deal with this php script further.

      Next, you can update the project with the script for forming 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 will appear in the future. for newbies.

      The downloaded php project of the site, updated with new scripts, can now be compared with the result of the above described 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. At the top left of the template, the menu of the first section should expand, as shown in the picture below.

      Go and melt into your favorite social media

      Because it expands the contents of the menu.php module. Below will be presented our own development of the 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 variants of the code, which have minor differences (the difference will be explained later).

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

      /index.html / razdel_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 in sections:

      / razdel_1 / podzaderl_1 / /razdel_1/podzaderl_1/articles_1.html /razdel_1/podzaderl_1/articles_2.html ... /razdel_1/podzaderl_2/articles_1.html /razdel_1/podzaderl_2/articles

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

      I suggest to create 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, the menu style is also presented in CSS, to immediately make it more or less beautiful. Naturally, this style is given for reference only, since the designs of the sites are very different.

      The code for styling the menu in CSS:

      .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 PHP menu implementation, which is a bit simplistic.

      The first version of the PHP menu code

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

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

    The second part contains the output of the menu through the for loop. The loop compares the site 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 the menu is displayed on the site. That is, the array must be filled in the order in which the menu is to be displayed.

    Note:
    In case the URL (addresses) of the heading of the sections are of the form:
    / razdel_1
    or such
    /razdel_1/nazvanie_razdela.html
    then in array_menu you need to write an exact match:
    $ array_menu [$ i] ["url"] = "/ razdel_1"
    or for the second case:
    $ array_menu [$ i] ["url"] = "/ razdel_1 / nazvanie_razdela.html";

    How does the first menu option work?
    It only highlights the menu if you are at the address of the section header. For example, if the page address is /razdel_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 the articles that are in the sections.

    The second version of the PHP menu code

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

In this article, I will show you how you can create multilevel menu in PHP and MySQL... Of course, you can think of many options for its creation, but judging by the number of your questions on this topic, you need an example. And I will give it in this article. I note right away that this article makes sense only for those who know PHP and knows how to work with MySQL... Everyone else first needs to go through this one, 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).

The table has been sorted out, now it's time PHP code... Full Php code is shown 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
$ childrens = array (); // Array for matching children to their parent
foreach ($ items as $ item) (
if ($ item ["parent_id"]) $ childrens [$ item ["id"]] = $ item ["parent_id"]; // Fill the array
}
function printItem ($ item, $ items, $ childrens) (
/ * Display the menu item * /
echo "

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

      This code is completely 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 comment carefully on the output code multilevel menu in PHP and MySQL, but, of course, it is not the most transparent and already requires quite good initial knowledge. If you still do not know well PHP and MySQL, then first I strongly recommend that you go through this

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

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

      • ID- identifier
      • Title- Menu name
      • Parent- Parent category by default 0

      The field is responsible for branching the menu Parent if Parent = 0, then this category is the parent. 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 you can see from the table, the parent category has Cars there are two descendants - this Mazda and Honda field related Parent... And the category Motorcycles two descendants are Kawasaki and Harley... However, the Boats category has no descendants. Hope you figured out 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 table data `categories` - 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 work algorithm consists of the following:

      Create a database connection

      query ("SET NAMES" utf8 ""); / * * This is the "official" object-oriented way to do it * however $ connect_error did not work until PHP 5.2.9 and 5.3.0. * / if ($ mysqli-> connect_error) (die ("Connection error (". $ mysqli-> connect_errno. ")". $ mysqli-> connect_error);) / * * If you need to be sure of compatibility with versions before 5.2 .9, * better to use code like this * / if (mysqli_connect_error ()) (die ("Connection error (". Mysqli_connect_errno (). ")". Mysqli_connect_error ());)

      Writing a function to get data from the Categories table

      // Get the array of our menu from the database as an array function getCat ($ mysqli) ($ sql = "SELECT * FROM` categories` "; $ res = $ mysqli-> query ($ sql); // Create an array where the key of the array 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.

      Solid Wood Build Function by Tommy Lacroix

      // Function of building 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 iterate over the $ dataset array [$ node [" parent "]] [" childs "] [$ id] = & $ node;)) return $ tree;)

      We get an array in the form of a tree

      Entire script

      query ("SET NAMES" utf8 ""); / * * This is the "official" object-oriented way to do it * however $ connect_error did not work until PHP 5.2.9 and 5.3.0. * / if ($ mysqli-> connect_error) (die ("Connection error (". $ mysqli-> connect_errno. ")". $ mysqli-> connect_error);) / * * If you need to be sure of compatibility with versions before 5.2 .9, * it is better to use this code * / if (mysqli_connect_error ()) (die ("Connection error (". Mysqli_connect_errno (). ")". Mysqli_connect_error ());) // Get the array of our menu 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;) // Tommy Lacroix array tree building function 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 over the $ dataset array [$ node ["parent"]] ["childs"] [$ id] = & $ node;)) return $ tree;) // Get prepared th data array $ 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 [" childs "])."
      ";) $ menu. ="
    • "; return $ menu;) / ** * Recursively read our template ** / function showCat ($ data) ($ string =" "; foreach ($ data as $ item) ($ string. = tplMenu ($ item); ) return $ string;) // Get HTML markup $ cat_menu = showCat ($ tree); // Display echo "
        ". $ cat_menu."
      "; ?>

      Result of work

      Multilevel menu in PHP + MySQL for admin panel

      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 ""; ?>

      Result of work

      Choose Cars → Mazda → → Mazda 3 → → → Sedan → → → Hatchback → → Mazda 6 → → → Liftback → → → Crossover → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → →>> Mazda CX → → Mazda MX → Honda Motorcycles → Kawasaki → Harley Boats