CodeIgniter load database in Controller or Model? - php

Model :
class Users_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
public function get_all_users() {
return $this->db->get('users');
}
}
Controller :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Users_model');
}
public function index() {
redirect('users/view_users');
}
public function view_users() {
$data['query'] = $this->Users_model->get_all_users();
$this->load->view('users/view_all_users', $data);
}
}
My question is where should i put the $this->load->database? In Model or Constructor? If possible tell me why?
And one more question, if i omit the $this->load->database, the error shown
"Undefined property: Users::$db". I'm expecting "Undefined property:
Users_model::$db".
Why is that? Is it looking for $db in both controller or model?
Thank you.
Note: i can connect to database just fine. What im actually ask is if i want to use $this->load->database(). Where should i put it? Controller or Model? And why?

You can either load the database in the controller or you can load it in the model.There's not much of a difference its just more neat and clean that all the interaction in the database is in the model and the controllers the one who connects both views and model.The controller here is like a middleman between the buyer and the seller.
load database in the controller
<?php
class Test_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database('default');
$this->load->model('test_model');
}
public function index()
{
$this->db->from('test');
$query = $this->db->get();
echo "<title>CodeIgniter SQlite</title>";
$data['db']=$query->result();
//print_r($data['db']);
$count = count($data['db']);
echo "Row count: $count rows<br>";
for ($i=0; $i < $count; $i++) {
echo $data['db'][$i]->text." ";
}
}
}
?>
load database in the model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test_model extends CI_Model
{
public $table1 = 'test';
public $table2 = '';
public function __construct()
{
parent::__construct();
$this->load->database('default');
}
public function check_db()
{
$this->db->from($this->table1);
$query = $this->db->get();
return $query->result();
}
}

Go to autoload.php in application/config/autoload.php and add this
$autoload['libraries'] = array('database'); // add database in array(now you dont need to load database at anywhere in project)
Make database connection settings in database.php, file located atapplication/config/database.php
now try this
class Users_model extends CI_Model {
function __construct() {
parent::__construct();
//$this->load->database(); <----remove this
}
public function get_all_users() {
return $this->db->get('users');
}
}

Related

Error in codeigniter call to undefined method with my model

I am new in codeigniter, I've read how to load some models with this framework. Now i have a problem regarding with using my model. I have an error of Message: Call to undefined method User_model::select().
My situation is simple, I want to implement a data table and i am using my model by it. Here is what my error comes:
//total records
foreach ($this->user->select("COUNT(*) AS count", $where, $join) as $key => $value) {
$data["iTotalDisplayRecords"] = $value->count;
$data["iTotalRecords"] = $value->count;
}
as you can see, i was using $this->user which is refers to my model i loaded in my constructor:
public function __construct() {
parent::__construct();
if (!$this->ion_auth->logged_in()){
redirect('auth/login', 'refresh');//redirect them to the login page
}
if (!$this->ion_auth->is_admin()){
redirect(base_url().'login', 'refresh');
}else{
$this->admin_id = $this->session->userdata('user_id');
$this->load->library("pagination");
$this->load->model('user_model','user');
}
}
Here is the code of my model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct() {
if ($this->ion_auth->logged_in()){
$this->user_id = $this->session->userdata('user_id');
$group = $this->ion_auth->get_users_groups($this->user_id)->result();
$this->group_id = $group[0]->id;
}
}
public $tbl_name = "users";
}
No this is not the way to call select in CI3. You have to write your own method in the model class then call that method.
I have rewrite your model, try this:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class User_model extends CI_Model
{
private $tbl_name = "users";
public function __construct()
{
if ($this->ion_auth->logged_in()) {
$this->user_id = $this->session->userdata('user_id');
$group = $this->ion_auth->get_users_groups($this->user_id)->result();
$this->group_id = $group[0]->id;
}
}
public function select($select, $where, $join)
{
$this->db->select($select);
$this->db->from($this->$tbl_name);
$this->db->where($where);
$this->db->join($join);
return $this->db->get()->result();
}
}

CodeIgniter: $data access in all views

I need to access $data[] variables in whole site, in all views. I created TestLeangue controller and assign some values to $data but in all views say that variable is not defined
class TestLanguage extends MY_Controller
{
public function __construct() {
parent::__construct();
$this->lang->load("menu","english");
}
function index() {
$data['shipping'] = $this->lang->line('menu_shipping');
$this->load->view('templates/navigation', $data);
}
}
I echo and say that I have undefined variable.
<?= $shipping; ?>
Why don't you use that data like a global variable?
class MY_Controller extends ...
{
protected $data = [];
}
Then everytime when you extend your custom controller you will have access to the general data.
class MyCustomStackOverflowController extends MY_Controller
{
public function index()
{
$this->load->view('index', $this->data);
}
}
Also, you can use $this->data to load it with general information for current controller like:
class MyCustomStackOverflowController extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->data['title'] = 'Stackoverflow';
}
public function index()
{
...
}
}
Use Index of $data as a variable name ($shipping), to get the value that you have assigned as $data['shipping']
Controller
class TestLanguage extends MY_Controller
{
public function __construct() {
parent::__construct();
$this->lang->load("menu","english");
}
function index() {
$data['shipping'] = $this->lang->line('menu_shipping');
$this->load->view('templates/navigation', $data);
}
}
View :templates/navigation
<?php
print_r($shipping);
?>

How to load view file in core functions in codeigniter

Am trying to load view file in application/core/MY_Controller.php but its giving as follows.
Message: Undefined property: Edustaticlanding::$load
Filename: core/MY_Controller.php
Function is as follows in MY_Controller.php
function menu(){
$arrr = array();
return $arrdata['menu'] = $this->load->view('menu',$arrr,true);
}
And am calling this function in controller(Edustaticlanding.php) as follows.
function __construct(){
$this->menucontent = $this->menu();
print_r($this->menucontent); die;
}
Pls correct me.. where its going wrong.. thanks
On application/core/MY_Controller.php
Add public $data = array() like below
<?php
class MY_Controller extends CI_Controller
{
public $data = array();
public function __construct()
{
parent::__construct();
$this->data['menu'] = $this->menu();
}
public function menu(){
return $this->load->view('menu', NULL, TRUE);
}
}
On the controller then once add public $data = array(); you can access the menu on view
You have to use $this->data now on controller
<?php
class Example extends MY_Controller {
public $data = array();
public function index() {
$this->data['title'] = 'Welcome to Codeigniter';
$this->load->view('example', $this->data);
}
}
On the example view now you can echo
<?php echo $menu;?>
Add extends CI_Controller to your core controller like following codes:
class MY_Controller extends CI_Controller {
Please check below mentioned solution. You need to call parent constructor first. So it will load all basic configurations.
First extent CI_Controller class and call parent constructor like describe below
class MY_Controller extends CI_Controller {
public function __construct{
parent::__construct();
}
}
Please let me if it not works.

Extending models in codeigniter 3

What I'm trying to do on the surface seems simple, basic OOP PHP but I just can't get it working. I have a controller class which is calling a model, that model extends another model of mine but it throws an error saying it can't find it:
Controller (Welcome.php):
public function __construct()
{
parent::__construct();
$this->load->model('users_model');
}
public function index()
{
$this->users_model->getAll();
}
Users Model (User_model.php):
class Users_model extends Base_model
{
public function __construct()
{
parent::__construct();
}
}
Base Model (Base_model.php):
class Base_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getAll($table)
{
$query = $this->db->query('Query here');
return $query;
}
}
This gives me the error Fatal error: Class 'base_model' not found in /ci/application/models/Users_model.php on line 3
Save your Base_model in application/core named as Base_model.php with following code.
class Base_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getAll($table=FALSE)
{
$query = $this->db->query('Query here');
return $query;
}
}
Save User_model in application/models named as User_model.php having following code
class User_model extends Base_model
{
public function __construct()
{
parent::__construct();
}
}
Then make a controller Welcome.php in appliation/controllers having following code with extending CI_Controller
public function __construct()
{
parent::__construct();
$this->load->model('user_model');//loads user_model
}
public function index()
{
$data = $this->user_model->getAll(); //need a variable to hold return data
}
You just have to locate the Base_model in your Users_model like below code and you can access the functions of base model easily.
require('application/models/base_model.php');
class User_model extends Base_model
{
function __construct()
{
parent::__construct();
}
}

CodeIgniter - constructors in models

So here is my controller:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
$this->search_model->search_result = $_POST;
}
public function index()
{
$data['results'] = $this->search_model->get_results();
$this->load->view('search_results', $data);
}
And here is my model:
class Search_model extends CI_Model {
protected $search_query;
function __construct($search_query)
{
parent::__construct();
$this->load->database();
$this->search_query = $search_query;
}
But this doesn't seem to work. What I want to do is pass the posted form ($_POST) to my model, then do stuff with it. But it seems messy to pass $_POST to each method of my model. My plan is to extract the variables sent with $_POST and construct these as properties such as $website_url, $text_query etc..., then call these in methods with $this->website_url;
I'm relatively new to CodeIgniter so just getting to grips with the basics
for your special purpose you can try this code
Controller:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
$this->init();
}
private function init()
{
$this->search_model->init( $this->input->post() );
}
public function index()
{
$data['results'] = $this->search_model->get_results();
$this->load->view('search_results', $data);
}
model:
class Search_model extends CI_Model {
protected $search_query;
function __construct()
{
parent::__construct();
$this->load->database();
}
public function init( $search_query )
{
$this->search_query = $search_query;
}
you have protected $search_query; which you can't access it from your controller.
You either have to change it to public or create getter and setter for it. or just getter depending on your domain/business logic.
And it should have been obvious as you should get an error saying
Fatal error: Cannot access protected property in file some/path/to/file!
Don't put the 'search query' in your model constructor.
Controller:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
}
public function index()
{
if ($this->input->server('REQUEST_METHOD') == 'POST')
{
// you should probably validate/clean the post data instead
// of sending it straight to the model
$results = $this->search_model->get_where($_POST);
}
else
{
// if it's not a post, you probably need something...
// either here, or somewhere in your view to handle empty data
$results = array();
}
$data['results'] = $results
$this->load->view('search_results', $data);
}
Your Model:
class Search_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database(); // <--- you may want to autoload 'database' library
}
function get_where($where)
{
$this->db->where($where);
// add select, order, joins, etc here
return $this->db->get('mytable'); // whatever your table name is
}

Categories