2

I'm trying to insert a number into the database from within a library using,

   $data = array(
   'id' => $id,
   'so' => '1',
   'username' => $username
);

$this->db->insert('db', $data); 

but whenever I run it, I get "Fatal error: Call to a member function insert() on a non-object in"

Anyone know why?

Thanks

1
  • 1
    this seems to concern $this->db. it appears its not what you think it is, and it doesnt have a member function called insert, and is not even an object at all Commented Mar 23, 2011 at 5:14

2 Answers 2

3

If you're doing this inside a library, you can't reference the $this object like you normally do in a model. Instead, you'll need to load an instance of CI like so:

$CI =& get_instance();

Then you should be able to insert a record into the database like this:

$CI->db->insert('db', $data);

Don't forget to load the database library as well if it's not in autoload.

Sign up to request clarification or add additional context in comments.

1 Comment

Because Codeigniter has deprecated support for PHP4, and the requirement is PHP5 now, all variables are assigned by reference so you don't need the ampersand in there. You can just use $CI = get_instance();
0

In a library "$this" refers to the class that you are coding (OOP concepts).

The DB object is part of the CI superobject. So in order to use db in your class you will have get a reference to the CI object like this

$CI =& get_instance();

And then rewrite your insert statments like this

$CI->db->insert('db', $data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.