MySQL insert inside library with codeigniter
I'm trying to insert a number into the database from within a library u开发者_如何学JAVAsing,
$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
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.
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);
精彩评论