Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 950599
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T23:35:34+00:00 2026-05-15T23:35:34+00:00

I have a MySQL singleton class written in PHP. Its code is listed below:

  • 0

I have a MySQL singleton class written in PHP. Its code is listed below:

class Database {
    private $_result = NULL;
    private $_link = NULL;
    private $_config = array();
    private static $_instance = NULL; 

    // Return singleton instance of MySQL class
    public static function getInstance(array $config = array()) {
        if (self::$_instance === NULL) {
            self::$_instance = new self($config);
        }

        return self::$_instance;
    }

    // Private constructor
    private function __construct(array $config) {
        if (count($config) < 4) {
            throw new Exception('Invalid number of connection parameters');  
        }

        $this->_config = $config;
    } 

    // Prevent cloning class instance
    private function __clone() {}

    // Connect to MySQL
    private function connect() {
        // Connect only once
        static $connected = FALSE;

        if ($connected === FALSE) {
            list($host, $user, $password, $database) = $this->_config;

            if ((!$this->_link = mysqli_connect($host, $user, $password, $database))) {
                throw new Exception('Error connecting to MySQL : ' . mysqli_connect_error());
            }

            $connected = TRUE;

            unset($host, $user, $password, $database);      
        }
    } 

    // Perform query
    public function query($query) {
        if (is_string($query) and !empty($query)) {
            $this->connect();
            if ((!$this->_result = mysqli_query($this->_link, $query))) {
                throw new Exception('Error performing query ' . $query . ' Message : ' . mysqli_error($this->_link));
            }
        }
    }

    // Fetch row from result set
    public function fetch() {
        if ((!$row = mysqli_fetch_object($this->_result))) {
            mysqli_free_result($this->_result);
            return FALSE;
        }

        return $row;
    }

    // Get insertion ID
    public function getInsertID() {
        if ($this->_link !== NUlL) {
            return mysqli_insert_id($this->_link); 
        }

        return NULL;  
    }

    // Count rows in result set
    public function countRows() {
        if ($this->_result !== NULL) {
           return mysqli_num_rows($this->_result);
        }

        return 0;
    }  

    // Close the database connection
    function __destruct() {
        is_resource($this->_link) AND mysqli_close($this->_link);
    }    
}

I also have this recursive function which must returns a full category tree (the SQL table and its content can be found here):

function getCategories($parent = 0) {
    $html = '<ul>';    
    $query = "SELECT * FROM `categories` WHERE `category_parent` = '$parent'";
    $database->query($query);    
    while($row = $database->fetch()) {
        $current_id = $row->category_id;
        $html .= '<li>' . $row->category_name;
        $has_sub = 0;
        $query = "SELECT `category_parent` FROM `categories` WHERE `category_parent` = '$current_id'";
        $database->query($query);
        $has_sub = $database->countRows();

        if ($has_sub > 0) {        
            $html .= getCategories($current_id);
        }

        $html .= '</li>';
    }

    $html .= '</ul>';
    return $html;
}

Now, the problem is that the function returns only 3 categories, not the full tree. I rewrote the function using plain MySQL functions (mysql_query(), mysql_fetch_object() etc.) and it returns the right result.

So my conclusion in that there’s something wrong with that class. Note that I’ve been using this class in most of my projects, but never had this issue.

Any idea what?

Thanks.

EDIT: Trying to make it to return an associative array

function getCategories($parent = 0) {
    global $database;
    $categories = array();

    $query = "SELECT * FROM `categories` WHERE `category_parent` = '$parent'";
    $database->query($query);    
    while($row = $database->fetch()) {
        $categories[] = array('id' => $row->category_id, 'name' => $row->category_name);        
    }

    for ($i = 0; $i < count($categories); $i++) {

        $categories[$i]['id']['children'] = getCategories($categories[$i]['id']);

    }

    return $categories;
}

The code above returns the following array, but is not quite ok:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Categoria 1
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 4
                            [name] => Categoria 1.1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 7
                                            [name] => Categoria 1.1.2
                                            [children] => Array
                                                (
                                                )

                                        )

                                )

                        )

                    [1] => Array
                        (
                            [id] => 5
                            [name] => Categoria 1.2
                            [children] => Array
                                (
                                )

                        )

                    [2] => Array
                        (
                            [id] => 6
                            [name] => Categoria 1.3
                            [children] => Array
                                (
                                )

                        )

                )

        )

    [1] => Array
        (
            [id] => 2
            [name] => Categoria 2
            [children] => Array
                (
                )

        )

    [2] => Array
        (
            [id] => 3
            [name] => Categoria 3
            [children] => Array
                (
                )

        )
)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T23:35:35+00:00Added an answer on May 15, 2026 at 11:35 pm

    The problem that you’re seeing is that you a running other queries over your first query. So after you recurse through the first branch the function fails because it goes back to the original which loop and finds that its already at the end of the resulting rows from the first branch (3 levels of recursion in).

    A quick fix would be to rewrite your function using two loops instead of just one. You can also optimise the function this way too by reducing the number of DB calls you have to make.

    Your first query is fine. But in your while loop, just grab the appropriate id and name elements and store them in an array. Then reloop through the array that you just created to recurse. Also, you can eliminate several queries by not running a “check” query. Just recurse – and if there are no elements the id:name array – return an empty string.

    EDIT: an example (untested)

    function getCategories($parent = 0) {
        $categories = array();
        $html = "<ul>";
        $query = "SELECT * FROM `categories` WHERE `category_parent` = '$parent'";
        $database->query($query);    
        while($row = $database->fetch()) {
            $categories[$row->category_id] = $row->category_name;
        }
        foreach($categories as $cid=>$category) {
            $html .= "<li>{$row->category_name}";
            $inner = getCategories($cid);
            if($inner != "<ul></ul>")
                $html .= $inner;
            $html .= "</li>"
        }
        $html .= "</ul>";
        return $html;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 499k
  • Answers 500k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This is not pretty but it works: rm -R $(ls… May 16, 2026 at 12:45 pm
  • Editorial Team
    Editorial Team added an answer Yes. Override the base1 and base2 methods in Derived to… May 16, 2026 at 12:45 pm
  • Editorial Team
    Editorial Team added an answer No, you can't. Unfortunately, UIEvent doesn't expose any public way… May 16, 2026 at 12:45 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.