Codeigniter错误:致命错误:无法使用类型为CI_DB_mysql_result的对象作为数组

时间:2013-11-16 19:18:55

标签: php codeigniter

我正在尝试为树实现php codeigniter模型,每次运行我的控制器时,都会收到以下错误:

  

致命错误:无法使用CI_DB_mysql_result类型的对象作为数组   第50行的C:\ AppServ \ www \ tree \ application \ models \ Btree.php

我尝试在行

中修复此语法
$currentID = $row['id'];

但是,仍然会收到相同的错误消息。

我的模特功能是:

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 个答案:

答案 0 :(得分:2)

你的问题在于这一行:

while($row = $result)

您正在为整个查询对象设置$row。您希望遍历查询的结果

请改为尝试:

$query = $this->db->query($sql);
foreach($query->result_array() AS $row) {
    $currentID = $row['id'];
    ...

答案 1 :(得分:1)

更简单的解决方案是直接转换为数组:

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

答案 2 :(得分:0)

试试这个

    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();
    }
}