How to pass a variable from model to controller in codeigniter?

Member

by jerad , in category: PHP Frameworks , a month ago

How to pass a variable from model to controller in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a month ago

@jerad 

To pass a variable from the model to the controller in CodeIgniter, you can follow these steps:

  1. Declare the variable in the model: In your model, declare the variable that you want to pass to the controller. class Your_model extends CI_Model { public $your_variable; }
  2. Assign a value to the variable in your model's method: Inside the method where you want to pass the variable, assign a value to it. class Your_model extends CI_Model { public $your_variable; public function your_method() { $this->your_variable = "Your value"; } }
  3. Load the model in the controller: In your controller, load the model so you can access its methods and variables. class Your_controller extends CI_Controller { public function index() { $this->load->model('Your_model'); } }
  4. Call the model's method and access the variable: Finally, call the method in your controller and access the variable. class Your_controller extends CI_Controller { public function index() { $this->load->model('Your_model'); $this->Your_model->your_method(); $your_variable = $this->Your_model->your_variable; echo $your_variable; } }


In the example above, the your_method in the model is called, which assigns a value to the $your_variable. Then, in the controller, the your_variable is accessed and echoed.