Jump to content

Recommended Posts

Hello,

 

I need to make a function that will display all categories and subcategories from a mysql table.

 

In the mysql the table there is something like this: cat_id, cat_root;

 

if cat_root is 0 -> it is a main category. Otherways it means that cat_roots is pointing to the root category. For example:

 

Category 1 ( id 1 | cat_id 0 )

    Product 1( id 2 | cat_id 1)

        SubProcut 1 (id 3 | cat_id 2)

Category 2 (id 4 | cat_id 0 )

 

and so on. I hope you get the picture.

 

I'm looking for a way to call all the categories for a <select>. What I've done so far is something like this:

 

function makeSelectCategories($id = 0 ,$str = '",$spacing=""){

 

      $q = "SELECT * FROM `categories` WHERE `cat_root` = ".$id;

 

      $r = mysql_query($q) or die(mysql_error());

 

      if(mysql_num_rows($r) == 0)

      return false;

 

      while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

 

          $str .= "<option>".$spacing.$row['cat_title']."</option>";

 

        $str .= makeSelectCategories($row['cat_id'],$str,$spacing." ");

 

        }

return $str;

 

}

 

echo "<select>";

echo makeSelectCategories();

echo "</select>";

 

I hope you get what I mean. Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/135332-recursive-function/
Share on other sites

try

function makeSelectCategories($id = 0, $spacing=""){

      $q = "SELECT * FROM `categories` WHERE `cat_root` = ".$id;

      $r = mysql_query($q) or die(mysql_error());
      $str = '';
      //if(mysql_num_rows($r) == 0)
      //return false;

       while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

          $str .= "<option>".$spacing.$row['cat_title']."</option>";

         $str .= makeSelectCategories($row['cat_id'], $spacing." ");

        }
return $str;

}

Link to comment
https://forums.phpfreaks.com/topic/135332-recursive-function/#findComment-705031
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.