phpcodeignitermodel-view-controllerresultset

How to present model method result data in the view of a CodeIgniter application


I am currently new to database query and other for codeigniter can not seem to quite get model working for what I am after.

I have tried loading db in direct to controller and that works OK. But if I call my model does not want to work nothing shows up.

Here is what I would like to achieve.

Controller

public function website_test_model()
{
    $this->load->model('admin/website/model_website');
    $results = $this->model_website->getWebsites();
    $data['websites'] = array();
    foreach ($results as $result) {
        $data['websites'] = array(
            'website_id' => $result['website_id'],
            'name' => $result['name'],
            'url' => $result['url']
        );
    }
    $this->load->view('website/websites', $data);
}

View (Not Working From Controller Function Model Test)

<?php if ($websites) { ?>
    <?php foreach ($websites as $website) { ?>
        <?php echo $website['website_id']; ?>
        <br>
        <?php echo $website['name']; ?>
        <br>
        <?php echo $website['url']; ?>
    <?php } ?>
<?php } ?>

Model

class Model_website extends CI_Model
{
    public function getWebsites()
    {
        $this->db->select('*');
        $this->db->from('website');
        $this->db->where('website_id');
        $this->db->where('name');
        $this->db->where('url');
        $query = $this->db->get();
          
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return false;
        }
    }
}

CodeIgniter Demo: It works when I try it this way as said on CodeIgniter User Guide. Just the code above is the way I am after though no luck with trying to make model work.

public function website()
{    
    $results = $this->db->get('website'); // Works Direct From Controller OK.
    
    foreach ($results->result() as $row) {
        $data = array(
            'website_id' => $row->website_id,
            'name' => $row->name,
            'url' => $row->url
        );
    }
    
    $this->load->view('website/website', $data);
}

Solution

  • you are doing wrong in you model file

    <?php
    
    class Model_website extends CI_Model {
    
      function getWebsites() {
           $query =$this->db->get('website');
    
          if($query->num_rows() > 0) {
            return $query->result();
          } 
      }
    
    
    }
    

    1) In your model you are using where condition but $this->db->where('website_id'); but you not passing anything in your condition you have to do like this $this->db->where('website_id',$yourwebsite_id);