Fatal error: Cannot use object of type stdClass as

2019-01-08 20:56发布

问题:

I'm getting the error:

"Fatal error: Cannot use object of type stdClass as array in" on line 183

From this code:

$getvidids = $ci->db->query(
    "SELECT * FROM videogroupids " . 
    "WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");

foreach ($getvidids->result() as $row){
    $vidid = $row['videoid'];              //This is line 183
}

Anyone know what's wrong with the above code? Or what this error means?

回答1:

CodeIgniter returns result rows as objects, not arrays. From the user guide:

result()


This function returns the query result as an array of objects, or an empty array on failure.

You'll have to access the fields using the following notation:

foreach ($getvidids->result() as $row) {
    $vidid = $row->videoid;
}


回答2:

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.



回答3:

Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g

 $getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup'   AND used='0' LIMIT 10");

foreach($getvidids->result() as $key=>$myids)
{

  $vidid[$key] = $myids->videoid;  // better methodology to retrieve and store multiple records in arrays in loop
 }