• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use Model

#1
[eluser]Unknown[/eluser]
Is there any one know how to use models to access the database, I wrote the following code, is there anything wrong about it.

Code:
<?php
class Blogmodel extends Model
{
    var $title = '';
    var $content = '';
    var $date = '';

    function _construct()
    {
    //Call the model constructor
    parent::Model();
    }

    /*function Blogmodel()
    {
        $this->load->database();
    }*/

    function get_last_ten_entries()
    {
        $query = $this->db->get('entries',10);
        return $query->result();
    }

    function insert_entry()
    {
        $this->title = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date = time();

        $this->db->insert('entries',$this);
    }

    function update_entry()
    {
        $this->title = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date = time();

        $this->db->update('entries',$this,array('id',$_POST['id']));
    }
}

The above gives the following error....

[error]

A PHP Error was encountered
Severity: Notice

Message: Undefined property: Blogmodel::$load

Filename: test/blogmodel.php

Line Number: 24


Fatal error: Call to a member function database() on a non-object in C:\wamp\www\CodeIgniter\system\application\models\test\blogmodel.php on line 24

[\error]

Plz help me...., actually I want to insert in database using models. If you have the code for inserting in database using model,view and controller, plz send it to me.

#2
[eluser]nmweb[/eluser]
IT seems fine. Try enclosing your code between [ code ] and [ / code] in the future. It improves readability. Second thing, your function reads get_last_ten_entries() but you use
Code:
$query = $this->db->get(’entries’,3);
So you only get three.

#3
[eluser]xwero[/eluser]
What is the code you use to call this model, there will be the mistake i think.

#4
[eluser]Matthew Pennell[/eluser]
You only have one underscore in your constructor function, that might be causing a problem.

#5
[eluser]Michael Wales[/eluser]
You may also be having an issue with using $this in your update_entry() method. I do believe the $this object includes a lot more than you are expecting (such as the parent controller's name). You end up passing column names to the database that don't exist.

Change your code to:

Code:
function insert_entry()
    {
        $insert->title = $_POST['title'];
        $insert->content = $_POST['content'];
        $insert->date = time();

        $this->db->insert('entries',$insert);
    }

    function update_entry()
    {
        $update->title = $_POST['title'];
        $update->content = $_POST['content'];
        $update->date = time();

        $this->db->update('entries',$update,array('id',$_POST['id']));
    }


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


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