Good afternoon, the problem is as follows, there is an MSSQL database with fields: id (tinyint), tittle (ntext), parent_id (tinyint) id field is auto-increment points to the parent menu element ( id ), for example, if parent_id = 4 then this element should follow the element with id = 4 (multilevel array)

what I want, I want something to load the menu from the database, here’s the listing itself:

config.php

<?php ////////////////////////// НАСТРОЙКА СОЕДИНЕНИЯ С БД///////////////////////// $serverName = "isuo-db.chtpz.ru,1433"; $connectionInfo = array( "Database"=>"doc", "UID"=>"doc", "PWD"=>"isuodoc"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) { }else{ echo "Соединение не удалось, ошибка:"; die( print_r( sqlsrv_errors(), true)); } function get_cat() { global $conn; //запрос к базе данных $sql = "SELECT * FROM dbo.menu_user"; $result = sqlsrv_query( $conn, $sql ); if(!$result) { return NULL; sqlsrv_errors(); } $arr_cat = array(); if(sqlsrv_num_rows($result) != 0) { //В цикле формируем массив for($i = 0; $i < sqlsrv_num_rows($result);$i++) { $row = sqlsrv_fetch_array($result,sqlsrv_ASSOC); print_r($row); //Формируем массив, где ключами являются адишники на родительские категории if(empty($arr_cat[$row['parent_id']])) { $arr_cat[$row['parent_id']] = array(); } $arr_cat[$row['parent_id']][] = $row; } //возвращаем массив print_r($row); return $arr_cat; } } //////// ФОРМИРОВАНИЕ БЛОКА МЕНЮ ДЛЯ ПОЛЬЗОВАТЕЛЯ/////////////////////////// //вывод каталога с помощью рекурсии function view_cat($arr,$parent_id = 0) { //Условия выхода из рекурсии if(empty($arr[$parent_id])) { return; } echo '<ul>'; //перебираем в цикле массив и выводим на экран for($i = 0; $i < count($arr[$parent_id]);$i++) { echo '<li><a href="?category_id='.$arr[$parent_id][$i]['id']. '&parent_id='.$parent_id.'">' .$arr[$parent_id][$i]['title'].'</a>'; //рекурсия - проверяем нет ли дочерних категорий view_cat($arr,$arr[$parent_id][$i]['id']); echo '</li>'; } echo '</ul>'; }?> 

I call the function c index.php :

 view_cat($result); 

but for some reason does not see the variable:

 PHP Notice: Undefined variable: result in **C:\inetpub\wwwroot\stackoverflow\nw\modules\menu.php on line 32** 

if I just call the get_cat () function, it returns nothing, although in theory I should form an array

when printing an array

$ result = get_cat (); print_r ($ result);

also does not give anything

I spent the whole evening yesterday, I did not find a solution. I would be grateful if you tell me what to do with it)

In general, the structure is as follows: index.php

 <?php header("Content-Type:text/html;charset=utf8"); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="css/bootstrap-grid.css" rel="stylesheet"> <link href="css/mainstyle.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/media.css" rel="stylesheet"> <script src="js/jquery.min.js"></script> </head> <body> <header> <img src="img/logo.jpg" class="logo_img"> </header> <div class="container"> <div class="row"> <div class="col-md-2 no-float"> <nav> <?php include_once 'modules\menu.php'; get_cat(); ?> </nav> </div> <div class="col-md-10 no-float"> <h1>Заголовок</h1> TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT </div> </div> </div> </body> </html> 

menu.php

 <?php session_start(); if ( isset( $_GET['l']) ) { $_SESSION['levelacc'] = $_GET['l'];; } else { echo "Error enter"; } $dostup=$_SESSION['levelacc']; switch ($dostup) { case "user": //вывод меню include 'core\config.php'; get_cat(); echo '<div style="width:300px;float:left; padding:10px; border:1px solid #074776">'; echo '</div>'; break; case "spec": echo "MENU FOR SPEC"; break; case "oper": include 'modules\modlvl\l3.php'; break; } ?> 
  • also empty is nothing - b.tard2016
  • added, and added a topic above, so that the full picture was shown, I just sit with it for 2 years, my head doesn’t work) just do not swear, I'm just learning) - b.tard2016
  • hmmm does not give anything ( - b.tard2016
  • in the base itself all the rules) gave the whole table as it should be - b.tard2016

1 answer 1

Try this function:

 function get_cat() { global $conn; $sql = "SELECT * FROM dbo.menu_user"; $result = sqlsrv_query($conn, $sql); if (false === $result) { die( print_r(sqlsrv_errors(), true)); } //var_dump(sqlsrv_num_rows($result)); $arr_cat = array(); while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) { $arr_cat[(int) $row['parent_id']][] = $row; } return $arr_cat; } 
  • Thank you, the array came out, and explain to the stupid that I did not so - b.tard2016
  • @ b.tard2016, I don’t know :) Probably the point is in the constant sqlsrv_ASSOC , but it was necessary SQLSRV_FETCH_ASSOC . And maybe in something else. When writing code, look in the manual. There are a bunch of (usually) usage examples for each function. Here is php.net/manual/ru/function.sqlsrv-fetch-array.php - Visman
  • Can you tell me more?) In config.php there is a function view_cat function (I put all this in the listing at the top) when I call it from the menu.php file (view_cat ($ result);) there is an error that does not see the variable, although get_menu function lies in the same file (conf.php) and it is connected by the Internet - b.tard2016