Welcome Guest, Not a member yet? Register   Sign In
Attempting my 1st model... but beginning to struggle!
#1

[eluser]JamesTaylor[/eluser]
So i am trying to get my 1st model up and running with CodeIgniter...

I have built a template page that contains the header and footer elements that will be consistant throughout the site. I then have a controller which is passing various information to the page via and array called $data - these are elements such as the page title, h1 tag, h2 tag etc. This is all working fine.

Here is my controller:

Code:
class Home extends Controller {

//Home Page
    function index(){
    $data['main_content'] = 'Home';
    $data['title'] = 'Welcome to the Golf Club';
    $data['h1'] = 'Golf Club';
    $data['h2'] = 'Welcome to the Golf Club';
    $data['BodyClass'] = 'Home';
    $data['FlashFile'] = 'crossfade_xml';
    $data['Image1'] = 'Image1.jpg';
    $data['Alt1'] = 'Pict1.jpg';
    $data['Image2'] = 'Image1.jpg';
    $data['Alt2'] = 'Pict2.jpg';
    $data['Image3'] = 'Image1.jpg';
    $data['Alt3'] = 'Pict3.jpg';
    $data['Image4'] = 'Image1.jpg';
    $data['Alt4'] = 'Pict4.jpg';
        
    $this->load->view('template', $data, $NextComp);
    }
}

Towards the footer of the page i am attempting to have a section of dynamic content that will show the next competition, the next social event and latest news by referencing a database - (the site is for a golf club).

i've set a model to select the next competition as follows:

Code:
class NextComp extends Model {

    function index()
    {

        $datetoday = time();
    
        $query = $this->db->query('
                SELECT CompName
                , CompFormat
                , CompDate
                FROM clubcompetitions
                WHERE CompDate + 86399 >= $datetoday
                ORDER BY CompDate ASC
                LIMIT 0, 1');
        return $query();
    }

}

I have already built this once in straight php and the code works, although it may not be the best method of doing it as am still learning! I am attempting to transport the existing code into CodeIgniter to learn the way it works.

Anyway, I now need to setup the controller to to call the method and pass the resulting information to the view which is where i am struggling to get my head around it.

I am currently trying to add this to my controller:

Code:
//Select Next Comp from DB for footer
    $this->load->model('NextComp');
    $NextComp = array();
    if($query = $this->NextComp->index())
    {
        $NextComp['results'] = $query;
    }
    
    //Loads view & passes $data and $NextComp
    $this->load->view('template', $data, $NextComp);
    }

and then display it in the view with:

Code:
<?php echo $results['CompName']; ?>

but i get an error saying that 'results' is an undefined variable?

As i say i am just starting out with CodeIgniter and have got this far from following various tutorial and some trial and error so i may be miles away from a working solution or almost there, i don't know as i've been going round in circles for the last few hours!

can anyone give me a point in the right direction please, it'd be much appreciated!

Thanks

James
#2

[eluser]stommert[/eluser]
hi,

I think you're returning an object in stead of an array,
try
return $query->result_array();

check out the documentation on active record.

gr
#3

[eluser]JamesTaylor[/eluser]
i've done some reading on active record as suggested and i still can't get anything working... surely it can't be this difficult!

I have made my sql more basic to try and get something working as a starting point, heres what i have:

Code:
class NextComp extends Model {

    function index()
    {
        $this->db->select('CompName, CompFormat, CompDate');
        $this->db->where('CompID', '1');
        $this->db->from('clubcompetitions');
        
        $query = $this->db->get();
        
        
    }
}

if i'm correct this should be selecting:

CompName, CompFormat, CompDate WHERE CompID=1 FROM clubcompetitions

Is there a way to check that my model is actually working at this point??

I now need to pass this retrieved info to the controller so it sits in $data['CompName'], $data['CompFormat'] and $data['CompDate']... this is where i am unsure what i should be doing.

Is the data automatically passed to the controller as it contains the code:

Code:
$this->load->model('NextComp');

or is that just loading the ability to use the model and do i somehow need to pass the info from the model to the controller with further code? and if so, where should that code be placed... in the model or the controller?
#4

[eluser]rogierb[/eluser]
Try
Code:
function get_clubcompetitions($id)
{
$this->db->select('CompName, CompFormat, CompDate');
$this->db->where('CompID', $id);
return $this->db->get('clubcompetitions');
}

And in your calling controller
Code:
$result = $this->NextComp->get_clubcompetitions('1')
echo $this->db->last_query(); //echo's the last used query

if($result->num_rows()>0)
{
$data['result'] = $result->row_array(); //this assumes one record.
}

in your view you can access the array like
Code:
echo $result['CompFormat'];
#5

[eluser]Wittner[/eluser]
Hi,

can I suggest you put the following in your controller (and in all your controllers while you're building your app.):

Code:
$this->output->enable_profiler(TRUE);

This will output lots of good information when you run your code. I've only discovered it recently and it makes a *huge* difference to debugging your script. Including variable values, posted values etc. it will also echo out the sql code which your active record produces,

cheers,

Wittner
#6

[eluser]JamesTaylor[/eluser]
Thanks, that works and i follow the logic of the code.

If the query returned a number of rows from the database how would the code change? i presume i would add a foreach loop in the if statement of the controller?... this is going to be my next step!

Thanks again

James
#7

[eluser]rogierb[/eluser]
I suggest you read the userguide, especially the part about "Generating Query Results".
You will find you answer there.
#8

[eluser]alboyd[/eluser]
Quote:
Code:
class NextComp extends Model {

    function index()
    {

        $datetoday = time();
    
        $query = $this->db->query('
                SELECT CompName
                , CompFormat
                , CompDate
                FROM clubcompetitions
                WHERE CompDate + 86399 >= $datetoday
                ORDER BY CompDate ASC
                LIMIT 0, 1');
        return $query();
    }

}

The main problem with this is that the query is asking to select WHERE CompDate + 86399 >= $datetoday. I think you would prefer it actually evaluate against the value of $datetoday rather than the literal string of "$datetoday".

If you have a variable within single quotes it remains as the letters of the variable name. If you use double quotes it expands out the variable and replaces with the value of the variable.

IMO: Also.. I would remove the Camelcase from your field names - gonna cause pain at some point I'd reckon.

Your model would also normally hold more than one function so I'd suggest you want to do something like:

Code:
class Competitions extends Model {


    function next_comp()
    {

        $datetoday = time();
    
        $query = $this->db->query('
                SELECT compname,
                compformat,
                compdate
                FROM clubcompetitions
                WHERE compdate + 86399 >= ?
                ORDER BY compdate ASC
                LIMIT 0, 1', $datetoday);

        return $query;
    }

}

Also just realised you were returning $query() instead of $query.

EDIT: Wow just did some more reading of the thread so far.. Seems you have a few more things going wrong here.

In your controller, using my model as shown above you would do something like this:
Code:
$this->load->model('Competitions');
$results = $this->Competitions->next_comp();

if ($results->num_rows() > 0)
{
    // do stuff with the data returned

}
else
{
    // deal with the fact no data was returned
}
#9

[eluser]JamesTaylor[/eluser]
I've been reading the userguide specifically the bits about active records and generating query results but unfortunately i'm not find them very insightful at the moment?

I have moved onto the next part that i need to achieve which is to query the database for the latest 3 news items which will then be displayed in the view. I Have tried various methods outlined in the userguide but to no avail. I have got it working but somehow i just feel the way i have done it is not the 'right' way.

Here's what i've done:

Model:
Code:
//Returns the latest 3 News Items
    function LatestNews()
    {    
        $this->db->select('NewsTitle');
        $this->db->order_by('NewsDate' , 'desc');
        $this->db->limit(3, 0);
        return $this->db->get('news');
    }

Controller:
Code:
//Select 3 Latest News Items from DB for footer
    $this->load->model('Notifications');
    $result = $this->Notifications->LatestNews();
    
    if($result->num_rows()>0)
    {
    $data['NewsTitle1'] = $result->row_array(0);
    $data['NewsTitle2'] = $result->row_array(1);
    $data['NewsTitle3'] = $result->row_array(2);
    }

View:
Code:
echo $NewsTitle1['NewsTitle']
      echo $NewsTitle2['NewsTitle']
      echo $NewsTitle3['NewsTitle']

is there a better way to access each row of the array in the controller section rarther than directly coding each array row to a unique $data variable in order to pass it to the view?
#10

[eluser]alboyd[/eluser]
It would good of you to comment on whether previous posts have assisted and whether they were the resolution to your enquiry..

Say you have $results like you have shown. Personally - most of the time unless I have to manipulate the data in the $results - I'll just send $results to the view and then if you want to present multiple rows I'll do it like this:

In the view (cut down on the html for the example):
Code:
<?php foreach($results->result() as $row) { ?>
    <tr>
        <td>&lt;?php echo $row->fieldname1; ?&gt;</td>
        <td>&lt;?php echo $row->fieldname2; ?&gt;</td>
    </tr>
&lt;?php } ?&gt;




Theme © iAndrew 2016 - Forum software by © MyBB