Rafael - Developer Rafael - Developer - 1 year ago 293
PHP Question

CodeIgniter error Invalid argument supplied for foreach()

I am trying to Select data from the datatbase but I get this error:

A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: controllers/hello.php
Line Number: 24


// system/application/controllers/hello.php

class Hello extends CI_Controller {

public function __construct()

function show_data() {

$query = $this->load->model('user');
foreach ($query->result() as $value) {
echo $value -> username;
echo $value -> password;
echo $value -> first_name;
echo $value -> last_name;


class User extends CI_Model {

function __construct()
// Call the Model constructor

function show()
$query = $this->db->get('user', 10);
return $query->result();

I'm looking at this tutorial: http://ellislab.com/codeigniter/user-guide/database/results.html

What does the error mean?

Answer Source

Your controller function should be like,

function show_data() {
    $query = $this->user->show();
    foreach($query as $value) {
        echo $value->username;
        echo $value->password;
        echo $value->first_name;
        echo $value->last_name;

Check here on how to load a model.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download