0

i need create a category engine with PHP and MySQL/MariaDB

Example:

  • Houses
    • House
    • Department
  • Cars
    • Car
      • New
        • 0 Miles
          • Toyota
            • Yaris
              • ...
              • ...
                • ...
                  • ...
                    • ...
                      • ...
              • ...
I tried creating the conventional way, but it seems inefficient.

SQL(Table):

CREATE TABLE `categories` (
  `id` int(11) NOT NULL auto_increment,
  `parent` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `icon` varchar(255) NOT NULL,
  `poster` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) engine="MyISAM" DEFAULT auto_increment="1" ;

PHP( with mysqli, pdo or mysql ):

class categories
{
    /**
    *   Fetch all subs( recursive )
    */  
    public function getSubsById ($id)
    {
        $rows = array();
        $list = array();
        $query = mysql_query("SELECT id, name, parent, icon, poster, description FROM categories WHERE parent = '$id' ORDER BY id");
        while ($row = mysql_fetch_array($query)) {
            $row["subs"] = $this->getSubsById($row["id"]);
            $rows[] = $row;
        }
        return $rows;
    }
    /**
    *   Fetch all parents categories
    */
    public function fetchParents ()
    {
        $rows = array();
        $query = mysql_query("SELECT id, name, parent, icon, poster, description FROM categories WHERE parent = 0 ORDER BY id");
        while ($row = mysql_fetch_array($query)) {
            $rows[] = $row;
        }
        return $rows;
    }
}

If you know some more efficient way please let me know what it is.

Maybe I should think about changing the database engine?

...Deploy APC, Memcache, Cache, Json, etc is another issue...

P.S: I want to create an online store system categories like Ebay :)

stew
  • 11,276
  • 36
  • 49
Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73

0 Answers0