问题
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();
}
}
回答1:
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'];
...
回答2:
just the simpler solution is to have direct conversion to arrays:
$result = $this->db->query($sql)->result_array();
回答3:
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();
}
}
来源:https://stackoverflow.com/questions/20022662/codeigniter-error-fatal-error-cannot-use-object-of-type-ci-db-mysql-result-as