Search code examples
codeignitercodeigniter-3

Unable to connect model page from controller page in code igniter


This is my database php page

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
'dsn'   => '',
'hostname' => '192.168.1.200',
'username' => 'name',
'password' => 'password',
'database' => 'codeignter_tutorial',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

I am unable to load model page from the controller page. This is the error am getting any help would be appreciated.

Fatal error: Call to undefined method CI_Loader::models() in /var/www/html/bcit-ci-CodeIgniter-3.1.11-0-gb73eb19/bcit-ci-CodeIgniter-b73eb19/application/controllers/Welcome.php on line 16 A PHP Error was encountered Severity: Error

Message: Call to undefined method CI_Loader::models() Filename: controllers/Welcome.php Line Number: 16 Backtrace:

This is my controller page Welcome.php

    <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {


public function index()
{
    $this->load->view('dashboard');
}

public function __construct()
{
    parent::__construct();
    $this->load->helper(array("form","url"));
    $this->load->models('models');

    
}
public function login()
{
    $this->load->view('loginPage');
}

public function dashboard()
{
    $data['name']=$this->input->post('name');
    $data['age']=$this->input->post('age');
    $this->models->dbdata($data);


    }
}
?>

This is my model page called models.php

<?php
class models extends CI_model
{
        public function dbdata($inserttodb)
        {
            $this->db->insert("registration",$inserttodb);
            return $var->result_array();
        }
}
?>

Solution

  • This is how you load model from your controller:

    public function __construct()
    {
        parent::__construct();
        $this->load->model('models', 'your_model'); //use 'your_model' to reference your model
    }
    

    This is how you called your model:

    $this->your_model->dbdata($data); 
    //'your_model' is from constructor, 'dbdata' is the name of your function in model
    

    Then make sure the method accept the 'data':

    public function dbdata($data)
        {
          //your code goes here
        }