Fatal error: Cannot use object of type stdClass as array in
I'm g开发者_StackOverflow中文版etting 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?
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;
}
if you really want an array instead you can use:
$getvidids->result_array()
which would return the same information as an associative array.
Controller (Example: User.php)
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Users extends CI_controller
{
// Table
protected $table = 'users';
function index()
{
$data['users'] = $this->model->ra_object($this->table);
$this->load->view('users_list', $data);
}
}
View (Example: users_list.php)
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user) : ?>
<tr>
<td><?php echo $user->name; ?></td>
<td><?php echo $user->surname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- // User table -->
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
}
精彩评论