0

i am new at php and trying to fetch data for my navigation bar via` database (mysql) but its showing:

Allowed memory size of 134217728 bytes exhausted (tried to allocate 16384 bytes

<?php
$con=mysqli_connect("localhost","root","","menu");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Perform queries 

function get_menu_tree($id) 
{
    global $con;
    $menu = "";
    $sqlquery = " SELECT * FROM mymenu";
    $res=mysqli_query($con,$sqlquery);
    while($row=mysqli_fetch_array($res,MYSQLI_ASSOC)) 
    {
           $menu ="<li><a href='".$row['link']."'>".$row['title']."</a>";

           $menu = "<ul>".get_menu_tree($row['id'])."</ul>"; //call  recursively

           $menu = "</li>";

    }

    return $menu;
} 
?>
<h1>Create Nested menu Tree by Mysql php</h1>
<ul class="main-navigation">
<?php echo get_menu_tree(1);//start from root menus having id 0 ?>
</ul>
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
  • Looks like you've made an infinite loop. You're probably missing some `WHERE`-clause in your SQL-query so you won't be fetching the exact same records on each iteration. – M. Eriksson Mar 23 '19 at 13:58
  • 2
    You re-fetch all database entries with every single iteration of your recursive function... – arkascha Mar 23 '19 at 13:58
  • Gotta make use of that `$id` parameter. – Jeto Mar 23 '19 at 14:01
  • 3
    `ini_set('memory_limit', '5Tb')` --- J/K --- whenever I see a small amount here `tried to allocate 16384 bytes` I immediately think infinite recursion. – ArtisticPhoenix Mar 23 '19 at 14:03
  • @ArtisticPhoenix - LOL – M. Eriksson Mar 23 '19 at 14:04
  • As I Suspected ...humm... Infinite recursion, modify your query (at the least) to include a `WHERE id = ` part. Right now you pull all the records, go through them, and call this again for each, which pulls all the records goes through them calls the function again `ad infinitum` etc... Until your memory is exhausted. . – ArtisticPhoenix Mar 23 '19 at 14:07
  • Also recursion is expensive to do in programming languages because off stacking.. Maybe you should be using a MySQL 8.0 recursive CTE or use other methods of quering hierarchical data see [How to create a MySQL hierarchical recursive query](https://stackoverflow.com/questions/20215744/how-to-create-a-mysql-hierarchical-recursive-query) or consider using [nested set model](https://en.wikipedia.org/wiki/Nested_set_model) for storing hierarchical data in SQL. – Raymond Nijland Mar 23 '19 at 14:23
  • what should i include in where condition my table has id as Primary Key? –  Mar 23 '19 at 17:20

0 Answers0