sys_debug
sys_debug

Reputation: 4003

CodeIgniter select and display result in view

I have the following simple code: The model:

function get_last_ten_entries()         
{
    $this->db->get('property');
}

controller:

public function load_recent()
{
    $data['info'] = $this->propertymodel->get_last_ten_entries();
    $this->load->view('load_property', $data);
}

view:

<?
echo $data['id'];
?>

This is not working. Am sure i am doing something wrong because the error shown says

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/load_property.php

Line Number: 2

Property is a table in the database in which there is a field called id. what's going wrong?

Thank you all

Upvotes: 2

Views: 12483

Answers (2)

jleft
jleft

Reputation: 3457

To fix the error, you'll need to use $info in your view, rather than $data as your array indexes in your controller correspond to variables in your view.

$this->db->get('property') returns all rows in the table property, but your function name suggests that you are trying to get the last 10 entries. I suggest you read CodeIgniter's Active Record documentation for more information. You also need to return your query.

You need to generate results from you query. CodeIgniter's Query Results documentation provides useful information on how to use the results of your query. What you're trying to achieve is a bit vague but you code could look something like this:

Model

function get_last_ten_entries()         
{
    return $this->db->get('property');  //Perform query (you'll need to update to select what you actually want from you database)
}

Controller

public function load_recent()
{
    $data['last_entries'] = $this->propertymodel->get_last_ten_entries();
    $this->load->view('load_property', $data);
}

View

foreach ($last_entries->result_array() as $entry)
{
   echo $entry['id'];
}

Or, if you rather use an object, instead of an array:

foreach ($last_entries->result() as $entry)
{
   echo $entry->id;
}

Upvotes: 4

Tom
Tom

Reputation: 3040

first of all, your function in model dosen't return anything. try this:

function get_last_ten_entries()         
{
    $result = $this->db->get('property');
    return $result->result_array();
}

when you fix that, you will have variable $info available in your view because Codeigniter evaluates given array to distinct variables on load->view( $view, $givenarray);

example

$data['variable1'] = 'first var';
$data['array'] = array('id' => 1, 'name' => 'myname' );
$this->load-view('view', $data);

would let you use variables in view file as following

echo $variable1; // echoes 'first var';
echo $array['name']; // echoes myname

Upvotes: 2

Related Questions