• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accessing database value in view

I'm new to Code Igniter and I've read all through the TOC and even have an existing application to use as a guide. However, I don't understand how to access a value from the database in one of my views.

This is part of my controller

class classifieds extends Controller {

    function classifieds() {





    function index() {

        $data['header_menu'] = 1;

        // get the categories
        $data['categories'] = $this->mdl_common->get_category_array();

        // get featured and most recent ads
        $data['featured_ads'] = $this->mdl_common->get_featured_ads();
        $data['recent_ads'] = $this->mdl_common->get_recent_ads();
        $data['features'] = $this->mdl_common->getFeatures();
        // generate and display the view
        $page = $this->load->view('view.header.php',$data,true);
        $page .= $this->load->view('view.sidebar.php',$data,true);
        $page .= $this->load->view('view.index.php',$data,true);
        $page .= $this->load->view('view.footer.php',null,true);
        echo $page;


This is the getFeatures function in the mdl_common Model as referenced in the Controller

function getFeatures() {
        $this->db->where("id = 1");    
        $query = $this->db->get("features");
        $features = $query->row();
        return ($features);

The table I am accessing in my mySQL database is called features. I have two fields in that table called leftTopNav and leftBotNav.

I would like to access the value of leftTopNav in my view in the file 'view.sidebar.php' (this is referenced in my controller and displays but I don't understand how to get the values.

I've tried $features['leftTopNav'], I've tried $features[0], I've tried $leftTopNav along with all sorts of other things. I just don't get it!!!

I know this is such a simple thing, but it has me stuck. Can someone tell me how to access this data in the form of a variable?


[eluser]GSV Sleeper Service[/eluser]
$query->row() returns an object. you access this in your view by using $features->leftTopNav
if you prefer the square bracket (array) notation, then use $query->row_array()

That worked, thanks so much!!!!

However, is there a better way to do this or am I doing it correctly?

If you are using PHP 5 then the most powerful and useful one is using Method Chaining. Use this as common syntax for all of your queries in model.
$query = $this->db->select('title')
         ->from('mytable as m')
         ->join('comments as c', 'c.id = m.id');
         ->where('m.id', $id)
         ->limit(10, 20)
if ($query->num_rows() > 0)    
$row = $query->row(); //For multiple row use $query->result_array()
return $row;
return false;

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.