2

I'm trying to implement a php codeigniter model for tree and every time I run my controller, I am getting the following error :

Fatal error: Cannot use object of type CI_DB_mysql_result as array in C:\AppServ\www\tree\application\models\Btree.php on line 50

I tried to fix this syntax in line

$currentID = $row['id'];

however, still getting the same error message.

My model function is:

public function fetchTree($parentArray, $parentID = null)
{
    // Create the query
    if ($parentID == null)
        $parentID = -1;

    $sql = "SELECT `id` FROM `{$this->tblName}` WHERE `id`= ". intval($parentID);

    // Execute the query and go through the results.
    $result = $this->db->query($sql);
    if ($result)
    {
        while ($row = $result)
        {
            // Create a child array for the current ID
            $currentID = $row['id'];
            $parentArray[$currentID] = array();

            // Print all children of the current ID
            $this->fetchTree($parentArray[$currentID], $currentID);
        }
        $result->close();
    }
}

3 Answers 3

4

Your problem is with this line:

while($row = $result)

You're setting $row to the entire query object. You want to loop through the results of the query.

Try this instead:

$query = $this->db->query($sql);
foreach($query->result_array() AS $row) {
    $currentID = $row['id'];
    ...
Sign up to request clarification or add additional context in comments.

Comments

2

just the simpler solution is to have direct conversion to arrays:

$result = $this->db->query($sql)->result_array();

Comments

0

try this

    public function fetchTree($parentArray, $parentID = null)
{

     // Create the query
        if ($parentID == null)
            $parentID = -1;

    $sql = "SELECT `id` FROM `{$this->tblName}` WHERE `id`= ". intval($parentID);

    // Execute the query and go through the results.
    $result = $this->db->query($sql);
    if ($result)
    {
        while ($row = $result)
        {
            // Create a child array for the current ID
            $currentID = $row['id'];
            $parentArray[$currentID] = array();

            // Print all children of the current ID
            $this->fetchTree($parentArray[$currentID], $currentID);
        }
        $result->close();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.