Reputation: 1340
I'm in the middle of making an webapplication with CodeIgniter, but I'm stuck on displaying database records to the user. Currently I have this:
** MODEL **
function showAllUsers()
{
$this -> db -> select('id, username, password');
$this -> db -> from('app_users');
$query = $this -> db -> get();
if($query -> num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
** CONTROLLER **
function index()
{
if($this->session->userdata('logged_in'))
{
$data = array();
$session_data = $this->session->userdata('logged_in');
$data['loggedin'] = $session_data['username'];
$type = $this->fillUserModule();
$naarview = array_merge( $data, $type );
//$data['title'] = ucfirst($page); //Capitalize first letter
$this->load->view('templates/header');
$this->load->view('navbar.php');
$this->load->view('pages/home', $naarview);
$this->load->view('templates/footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
function fillUserModule()
{
//Run the query for getting all users
$result = $this->user->showAllUsers();
if ($result)
{
var_dump($result);
return $result;
}
else
{
return false;
}
}
If I dump the result I get this, this is from the $result query:
array(2) {
[0]=> object(stdClass)#20 (3) {
["id"]=> string(1) "1"
["username"]=> string(3) "bob"
["password"]=> string(32) "81dc9bdb52d04dc20036dbd8313ed055"
}
[1]=> object(stdClass)#21 (3) {
["id"]=> string(1) "2"
["username"]=> string(4) "huub"
["password"]=> string(32) "258bb2089ad9345897565e3e7f023f6e"
}
}
But I cannot seem to access it in the View. I can access the 'loggedin' variable but that one is clearly identified, but the array of the actual users, coming from the model and controller, I cannot access it, probably because it is an array, which is an stdClass?
Do I need to convert these values to another array so I can access it?
Upvotes: 1
Views: 775
Reputation: 1681
Try this :
function fillUserModule()
{
//Run the query for getting all users
$result = $this->user->showAllUsers();
if ($result)
{
var_dump($result);
echo $result->username."<br />";
return $result;
}
else
{
return false;
}
}
You can use "->"
to access the object data like this : echo $result->username."<br />";
Upvotes: 1
Reputation: 22532
here you see how we send data to view from controller in codignator
function fillUserModule()
{
//Run the query for getting all users
$result = $this->user->showAllUsers();
if ($result)
{
$data['result']=$result;
//load view here
$this->load->view('home', $data);
}
else
{
return false;
}
}
In your viwe page you use
foreach($result as $val){
//your code here
}
Upvotes: 1
Reputation: 4739
Edit the controller like this
$this->load->view('pages/home', array('naarview' => $naarview));
And access it in home view page.
Upvotes: 1
Reputation: 1663
Use $query->result_array()
instead of $query->result()
. Result will be array, not object :)
Upvotes: 1