• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help converting a function to CI

#1
[eluser]macleodjb[/eluser]
Hi guys, I'm a little shaky with how i need to code this function now that i am using codeigniter, before i had a functions file which i would just include into the file i needed it in and just echo out what i needed at any time.

The function below is my old function and it would be placed into job_model.php. The functions its calling are functions that reside in Main_model.php. Obviously i'm getting an error with Main_model. Don't really know why, perhaps you can help.

Code:
function populate_subcat_array() {
    $catnames = $this->Main_model->get_industry;
        while ($industry = @mysql_fetch_array ($catnames, MYSQL_ASSOC)) {
        echo "cats[" . $industry['cat_id'] . "] = new Array();\n";
        $subcatnames = getsubcat($category['cat_id']);
            while ($subcatname = @mysql_fetch_array ($subcatnames, MYSQL_ASSOC)) {
            echo "  cats[" . $category['cat_id'] . "] [" . $subcatname['cat_id'] . "] = '" . $subcatname['cat_name'] . "';\n";
            }
        }
    }

#2
[eluser]JaRoLLz[/eluser]
CI use MVC. So, you should separate your app into model, view, controller.

As for that function, you should split it into M,V,C.

[model] In job_model, create a function to get the `cats` data then return an array that contains its data
[view] in a view file (e.g. subcat.php), create a layout to present the data
[controller] in your controller (e.g. Cats) create a function that will get data using the model then passing it to view file to show.

crude example:

MODEL: job_model.php
Code:
class Job_model extends Model {
  function Job_model() {
    parent::Model();
  }

  function getCats() {
    $query = $this->db->query('
      SELECT *
      FROM `cats`
    ');
    if ($query->num_rows() > 0) {
      return $query->result_array();
    } else {
      return array();
    }
  }
}

VIEW: subcat.php
Code:
<html>
<body>
<h1>Cats</h1>
&lt;? foreach ($catdata as $r): ?&gt;
  ID: &lt;?php echo $r['id'] ?&gt;
  Name: &lt;?php echo $r['name'] ?&gt;
  Desc: &lt;?php echo $r['desc'] ?&gt;
  <br>
&lt;? endforeach; ?&gt;
&lt;/body&gt;
&lt;/html&gt;

CONTROLLER: cats.php
Code:
class Cats extends Controller {
  function Cats() {
    parent::Controller();
  }

  function populate() {
    $this->load->model('job_model');
    $data['catdata'] = $this->job_model->getCats();
    $this-&gt;load->view('subcat',$data);
  }
}

p.s.: Adjust the code as needed. CMIIW!


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


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