Reputation: 2763
I am trying to insert data to mysql in codeigniter. Controller class :
class Ci_insert extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$data = array(
"USN" => "TRE5rCS89G",
"name" => "NITISH DOLAKASHARIA",
"branch" => "CS"
);
$this->load->model('ci_insert_model');
$this->ci_insert_model->addToDb($data);
}
}
Model Class :
class ci_insert_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function addToDb($data)
{
//var_dump($data);
$this->db->insert('class_record',$data);
}
}
But when I tried to run the code, it shows Fatal error: Call to a member function insert() on a non-object in C:\wamp\www\CodeIgniter\application\models\ci_insert_model.php on line 12
.
Whats wrong with the code above?
Upvotes: 2
Views: 23734
Reputation: 55
Add autoload libraries in config folder open autoload.php and set $autoload['libraries'] = array('database');
Upvotes: 3
Reputation: 5411
You have to use '$this->load->library('database')'
in the model before '$this->db->insert()'
or
autoload the database library. Go to config folder select autoload.php search for $autoload['libraries'] and replace your empty array() with array('database').
Upvotes: 3
Reputation: 4565
You're missing $this->load->database();
$this->db->method_name();
will only work when the database library is loaded.
If you plan on using the database throughout your application, I would suggest adding it to your autoload.php
in /application/config/
.
As others have mentioned, remove the CI_
prefix from your class names. CI_
is reserved for framework classes.
Upvotes: 10
Reputation: 704
Try out.
Controller : insert.php
class Insert extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$data = array(
"USN" => "TRE5rCS89G",
"name" => "NITISH DOLAKASHARIA",
"branch" => "CS"
);
$this->load->model('insert_model');
$this->insert_model->addToDb($data);
}
}
Model: insert_model.php
class Insert_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function addToDb($data)
{
//var_dump($data);
$this->db->insert('class_record',$data);
}
}
Please write capital first latter of class, don't add prefix like ci_
.
Upvotes: 1