Cannot load a model in codeigniter - codeigniter

I failed to load a model from my controller
This is the controller file, article.php:
<?php
class Article extends CI_Controller {
function show($id) { //id'ye gore getir
$this->load->model('articles_model');
$parameter = $this->articles_model>getarticle($id);
$this->my_template->build('article_view', $parameter);
}
}
?>
This is the model file, articles_model.php:
<?php
class Articles_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function Getarticle($id) {
parent::Model();
$query = $this->db->get_where('articles', array('id' => $id));
$data['articles'] = $query->result();
return $data;
$query->free_result();
}
}
?>
just to add, i even tried to load it from autoloader, still no chance, i assume something is wrong with the model, or the whole system broke.
up: the models loads without problems, if i put echo in __construct function, it works, however, i cannot call the getarticle function. geez
UP: I did it! according to http://grasshopperpebbles.com/codeigniter/codeigniter-call-to-a-member-function-on-a-non-object/
i used
$CI =& get_instance();
and called the function
$CI->articles_model->getarticle($id) and it called the function

It should be,
$CI =&get_instance();
$CI->load->model('articles_model');
$parameter = $CI->articles_model>getarticle($id);

There's a parse error in the following line:
$parameter = $this->articles_model>getarticle($id);
It should be:
$parameter = $this->articles_model->getarticle($id);
Does that fix your problem? If not, what error message are you seeing?

Leif's answer is the right one. Just to add one thing: you don't have to use the long variable name like $this->articles_model over and over, by using the second parameter:
$this->load->model('articles_model','artm');
$parameter = $this->artm->getarticle($id);
Just a little faster to type, and can reduce typos like the one in your sample.

Related

Error when calling procedures in code igniter

I am calling a procedure in code igniter and when I try to call another procedure I get the following error:
Error Number: 2014
Commands out of sync; you can't run this command now
call get_post_info($id)
Filename: C:/Apache24/htdocs/application/models/Posts_model.php
Line Number: 18
I think I need to clear the result set... not sure.
Here is my model:
<?php class Posts_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_post_ids($acc_id){
$query = $this->db->query('call get_post_ids('.$this->db->escape($acc_id).')');
return $query->row_array();
}
public function get_post($id)
{
$query = $this->db->query('call get_post_info($id)');
return $query->row_array();
}
}
In my controller:
$post_ids = $this->posts_model->get_post_ids(1);
foreach ($post_ids as $id){
array_push($data, $this->posts_model->get_post($id));
}
I didn't actually run these solutions, but I found some info that might be what you look for. First of all, check this post about the cause of the problem.
I suppose $query->free_result() should solve the problem:
public function get_post_ids($acc_id){
$query = $this->db->query('call get_post_ids('.$this->db->escape($acc_id).')');
$result = $query->row_array();
$query->free_result();
return $result;
}
And in case that doesn't work, this this may be a good solution for CodeIgniter.

How to use session_data in codeigniter throughout Website without including in particular view

Is there any other best way to use session_data in website.
How i set session in my project:
$sess_array = array('id' => $row->user_id,'name'=>$row->user_name,'email'=>$row->email,'condition'=>'','balance'=>$row->balance,'did_alloted'=>$row->did_alloted,'create_date'=>$row->create_date);
$this->session->set_userdata('logged_in', $sess_array);
when it comes to controller:
$data['id'] = $session_data['id'];
$data['name'] = $session_data['name'];
$data['email'] = $session_data['email'];
$data['balance']=$session_data['balance'];
$data['did_alloted']=$session_data['did_alloted'];
$data['create_date']=$session_data['create_date'];
$this->load->view('san-reception', $data);
and in my view. I use <?php echo $name ?> to get session_data.
So is there any method by which i can directly access session_data in view without including as $data.
$this->session->userdata('logged_in'); will be available directly in views and hence you just need to assigned this to a variable and then use that as array like bellow.
$userdata=$this->session->userdata('logged_in');
now variable $userdata contain all array field that you set in controller and hence you can use it as $userdata['id'], $userdata['name'] etc
public function __construct()
{
parent::__construct();
$data['session_data']=$this->session->user_data('logged_in');
}
public function some_function(){
$data['dummy']="";
$this->load->view('someview3',$data)
}
public function some_function1(){
$data['dummy']="";
$this->load->view('someview1',$data)
}
public function some_function2(){
$data['dummy']="";
$this->load->view('someview2',$data)
}
If you assign that into the constructor then it will call by automatically whenever a function calls in the controller.
you can view it in you view page by,
print_r($session_data);

CodeIgniter invoke variable from another function in the same controller

I have a problem. I want to access to a variable from another function. let me explain.
Controller
public function obtener_oplataforma_usuarios() {
$this->load->helper('form');
$this->load->model('usuarios_model');
$plataforma = $this->input->post('id_plataforma');
$data['records'] = $this>usuarios_model>obtener_plataformas_usuarios($plataforma);
$this->load->view('vista_plataforma_usuarios', $data);
}
function grupos($grupo){
$this->load->helper('form');
$this->load->model('usuarios_model');
$plataforma = 'BaD';
$data['records'] = $this->usuarios_model->obtener_grupos($plataforma, $grupo);
$this->load->view('vista_plataforma_usuarios', $data);
}
Model
function obtener_grupos($plataforma, $grupo){
$this->db->select('*');
$this->db->from('usuarios');
$this->db->where('Plataforma', $plataforma);
$this->db->where('grupos', $grupo);
$query = $this->db->get();
return $query->result();
}
I want to access to the variable platforma in the function obtener_oplataforma_usuarios from the function obtener_grupos I tried different things and I still have problems.
Can you help me to solve this issue. and I want to do that because I want to make a query with two validations one is group and the other platforma. My problem is the second one. I recibe the information of plataforma fine from a from this is in the function obtener_oplataforma_usuarios and is fine but I do not how to read this variable from the other function.
you lose minuses (-) in pointers :)
$data['records'] = $this>usuarios_model>obtener_plataformas_usuarios($plataforma);
must be:
$data['records'] = $this->usuarios_model->obtener_plataformas_usuarios($plataforma)
You can use a private variable in your class.
Create the variable above your __construct function, private $plataforma
Set the default value in your __construct function
Set and get in your public function using $this->plataforma
Implemented in your code:
private $plataforma;
public function __construct() {
parent::__construct();
$this->plataforma = "";
}
public function obtener_oplataforma_usuarios() {
$this->load->helper('form');
$this->load->model('usuarios_model');
$this->plataforma = $this->input->post('id_plataforma');
$data['records'] = $this>usuarios_model>obtener_plataformas_usuarios($this->plataforma);
$this->load->view('vista_plataforma_usuarios', $data);
}
function grupos($grupo){
$this->load->helper('form');
$this->load->model('usuarios_model');
$data['records'] = $this->usuarios_model->obtener_grupos($this->plataforma, $grupo);
$this->load->view('vista_plataforma_usuarios', $data);
}

CodeIgniter: loading multiple models in the same controller

I searched the whole Internet and either there is no one mentioning my problem, or I'm stupid, or maybe it's just a bad day for coding.
What's the situation:
controller "source"
model "source"
model "login"
The "login" model is loaded from autoload.php, then in each controller's constructor I have $this->login->check(), which is checking if the user is logged in (obviously). Then in some of the methods I'm using the "source" model to connect to the database.
I tried loading both of the models from the autoload array, I also tried to load them in the way described here, but it's obviously for an old CI version (the thread is from 2008) and I tried all the possible ways I had in my mind.
Anyway, the result is this:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Source::$login
Filename: controllers/source.php
Line Number: 10
Fatal error: Call to a member function check() on a non-object in ...\application\controllers\source.php on line 10
Any ideas what I'm missing or how to fix it...? I'm stuck for hours and I don't have any ideas what I could do...
Edit 1: here is the code from the "source" controller:
class Source extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('login');
$this->login->check();
}
function index() {
// Pagination config, getting records from DB
$this->load->view('templates/layout', $data);
}
function add() {
$this->load->model('source', '', true);
$btn = $this->input->post('btn');
if(isset($btn)) {
// More form validation
if($this->form_validation->run() == TRUE) {
if($btn == "Add") {
// here I am supposed to use the source model...
}
}
}
$data['page'] = 'source_add';
$this->load->view('templates/layout', $data);
}
}
?>
Edit 2: login.php:
<?php
class Login extends CI_Model {
function __construct() {
parent::__construct();
}
function authenticate($username, $password) {
// the login script comes here
}
function logged() {
if($this->session->userdata('logged') == true) {
return true;
} else return false;
}
function check() {
if(!$this->logged()) {
redirect('/authentication');
}
}
}
?>
Conventionally, the classname of Models should end with _model, so it not collides with controllers with the same name, so try changing
class Login extends CI_Model {
to
class Login_model extends CI_Model {
I resolved this issue by utilizing the hooks and turned the login process into a controller, thereby being able to access user information and setting access levels.
First I added the following to the hooks.php file in the config folder
$hook['post_controller_constructor'][] = array('function' => 'check_login','filename' => 'authority.php','filepath' => 'hooks');
Then I have the following functions in a hook file called authority.php
[EDIT]Having reviewed this I am going to change it to a pre_controller_constructor and see if I can remove what seems to be a double page flash on initial construct.[/EDIT]
function check_login(){
$CI =& get_instance();
$is_logged_in = $CI->session->userdata('is_logged_in');
if(!$is_logged_in){
$unauth_pages = array(your unauthorized pages go here);
if(!in_array($CI->router->class,$unauth_pages)){
$CI->session->set_userdata('before_login_url',current_url());
redirect('login');
}
}
}
function check_authority(){
$CI =& get_instance();
if($CI->session->userdata('usergroupID') == 'SUPADMIN'){return;}
$page = $CI->router->class ;
$method = $CI->router->method;
$method = ($method=='index')?'':$method;
$unauth_pages = array(your unauthorized pages go here);
if(in_array($page,$unauth_pages))return;
$user_group = $CI->session->userdata('usergroupID');
$CI->load->model('user_model');
if($user_group == 'ADMIN' || $user_group == 'USER'){
if($CI->session->userdata('timezone') == ''){
date_default_timezone_set('Canada/Pacific');
} else {
date_default_timezone_set($CI->session->userdata('timezone'));
}
}
if( !$CI->user_model->authorized_content($CI->session->userdata('usergroupID'),$page, $method)){
redirect('unauthorized');
}
}
With the above I dont have to worry about checking on each page but instead utilize the ci framework to do the checking for me.. if its not in the unauth page array then it is a page that requires authorization checking.
Hope this works for you.

Codeigniter MVC Sample Code

Hi
I am following the getting started guide for Codeigniterr given at http://www.ibm.com/developerworks/web/library/wa-codeigniter/
I have followed the instruction to create the front view and added controller to handle form submission. Ideally, when i submit the form, it should load the model class and execute the function to put details on the database, but instead it is just printing out the code of the model in the browser.
**Code of view (Welcome.php)**
----------------
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
$this->load->helper('form');
$data['title'] = "Welcome to our Site";
$data['headline'] = "Welcome!";
$data['include'] = 'home';
$this->load->vars($data);
$this->load->view('template');
}
function contactus(){
$this->load->helper('url');
$this->load->model('mcontacts','',TRUE);
$this->mcontacts->addContact();
redirect('welcome/thankyou','refresh');
}
function thankyou(){
$data['title'] = "Thank You!";
$data['headline'] = "Thanks!";
$data['include'] = 'thanks';
$this->load->vars($data);
$this->load->view('template');
}
}
/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
**Code of Model**
--------------
class mcontacts extends Model{
function mcontacts(){
parent::Model();
}
}
function addContact(){
$now = date("Y-m-d H:i:s");
$data = array(
'name' => $this->input->xss_clean($this->input->post('name')),
'email' => $this->input->xss_clean($this->input->post('email')),
'notes' => $this->input->xss_clean($this->input->post('notes')),
'ipaddress' => $this->input->ip_address(),
'stamp' => $now
);
$this->db->insert('contacts', $data);
}
**OUTPUT after clicking submit**
-----------------------------
class mcontacts extends Model{ function mcontacts(){ parent::Model(); } } function addContact(){ $now = date("Y-m-d H:i:s"); $data = array( 'name' => $this->input->xss_clean($this->input->post('name')), 'email' => $this->input->xss_clean($this->input->post('email')), 'notes' => $this->input->xss_clean($this->input->post('notes')), 'ipaddress' => $this->input->ip_address(), 'stamp' => $now ); $this->db->insert('contacts', $data); }
I have tried doing these things
1. Making all PHP codes executable
2. Change ownership of files to www-data
3. make permission 777 for whole of www
But, the code of model seems to be just printed ... PLEASE HELP
Just a few minor points that might help you:
In your controller, point the index method at the method you would like to call on that page. For example:
function index()
{
$this->welcome();
}
That will help keep things clean and clear, especially if anyone else comes in to work on the code with you later. I chose welcome because that's the name of your controller class and that will keep things simple.
In your model, this:
class mcontacts extends Model{
Should be:
class Mcontacts extends Model{
Capitalize those class names! That could be giving you the trouble you describe.
See here for more info on this: http://codeigniter.com/user_guide/general/models.html
Don't use camel case in your class or method names. This isn't something that will cause your code to fail, but it's generally accepted practice. See Codeigniter's PHP Style guide for more information on this: http://codeigniter.com/user_guide/general/styleguide.html
It's difficult to see with the formatting as it is, but do have an extra curly brace after the constructor method (mcontacts()) in the model? This would cause problems! Also although the code looks generally ok, there are probably better ways to use the framework especially if you do anything more complicated than what you've shown. For example, autoloading, form validation etc. Can I suggest you have a read of the userguide? It's very thorough and clear and should help you alot. http://codeigniter.com/user_guide/index.html

Resources