Rafael - Developer Rafael - Developer - 4 months ago 152
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


Controller:

<?php
// system/application/controllers/hello.php

class Hello extends CI_Controller {

public function __construct()
{
parent::__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;
}
}
}
?>


Model:

class User extends CI_Model {

function __construct()
{
// Call the Model constructor
parent::__construct();
}

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

Your controller function should be like,

function show_data() {
    $this->load->model('user');
    $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.