How to load model from hooks file in ci3 [duplicate] - codeigniter

This question already has answers here:
How do I load my models inside a codeigniter hook file
(2 answers)
Closed 5 months ago.
I'm trying to learn how to use hooks in ci3, is it possible to load a model from hooks file in CI3? because when I try to load the model it gives me this error:
A PHP Error was encountered
Severity: Warning
Message: Undefined property: Http_request_logger::$load
Filename: hooks/http_request_logger.php
Line Number: 9
And
An uncaught Exception was encountered
Type: Error
Message: Call to a member function model() on null
Filename: D:\xampp\htdocs\vobot-cms\application\hooks\http_request_logger.php
Line Number: 9
and here's my hooks code:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Http_request_logger {
public function activity_user() {
$CI = & get_instance();
$this->load->model('./activity_user/MActivityUser');
// log_message('info', 'GET --> ' . var_export($CI->input->get(null), true));
$post = log_message('info', 'POST --> ' . var_export($CI->input->post(null), true));
// log_message('info', '$_SERVER -->' . var_export($_SERVER, true));
$this->MActivityUser->insertLogActivity( $data = array(
'username' => (!$this->MActivityUser->getUsername() ? NULL : $this->MActivityUser->getUsername()),
// 'domain' => $_SERVER["SERVER_NAME"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => $post,
// 'ip' => $this->CI->input->ip_address(),
'create_date' => date('Y-m-d H:i:s'),
'cms_id' => $this->MActivityUser->getUserId()
));
return $data;
}
}

The error is that you are loading the CI instance into the $CI variable but you are not using it to load your model.
$CI = & get_instance();
$this->load->model('./activity_user/MActivityUser');
should be
$CI = & get_instance();
$CI->load->model('./activity_user/MActivityUser');

Related

An uncaught Exception was encountered. Call to undefined method Admin_model

Okay i've cloned a codeigniter code copy and use it to designed a app, recently i wanted to start a new app and did opened the downloaded copy again and started to program, but now i am getting the the above mentioned error, this code worked in my prevouis code but in this it isn't.
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Admin_model::get_stock_item()
Filename: C:\xampp\htdocs\francois\application\controllers\Admin.php
Line Number: 239
Here is my controller
///<?php
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Admin extends CI_Controller {
public function __Construct() {
parent::__Construct();
if(!$this->session->userdata('logged_in')) {
redirect(base_url());
}
$this->load->model('Admin_model');
}
function stock_adjustment($id)
{
$data = array(
'formTitle' => 'Stock Management',
'title' => 'Stock Management'
);
$data["data"] = $this->Admin_model->get_stock_item('', '', $id);
$this->load->view('frame/header_view');
$this->load->view('frame/sidebar_nav_view');
$this->load->view('stock/update_price', $data);
$this->Admin_model->Update_asset($id);
redirect( base_url('stock/stock_view'));
}
}
Model
///function get_stock_item($limit, $start, $id=0)
{
///if(empty($id)){
///$this->db->limit($limit, $start);
///$query = $this->db->get('tbl_stock');
///if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
///return $data;
}
/// return false;
///} else {
///$query = $this->db->get_where('tbl_stock', array('id' => $id));
///return $query->row_array();
}
}
Please as i said it worked in my othered app but not in this one code is exaclty the same.
The error message is quite clear: The class Admin_model does not have a method named get_stock_item(). Probably beause you have commented-out the definition of the method.
Change the line
///function get_stock_item($limit, $start, $id=0)
to
function get_stock_item($limit, $start, $id=0)
There's a lot of other code that is commented and, as it stands, I think you will get lots of other errors running that model method.

How to get base url in pre_controller hook in codeigniter

I am working on hook file, i am using pre_controller function of hook, but when i tried to use base_url() function in it, it is not working for me, it give me this error Call to undefined function base_url(), can anyone please help me to resolve this error ? here i have added my whole function
$hook['pre_controller'] = function()
{
$this->CI = get_instance();
$ci =& get_instance();
$router =& load_class('Router', 'core','uri','url');
$controller_name = $router->fetch_class();
$action_name = $router->fetch_method();
$segement = $router->uri->segment(2);
echo base_url(); die;
try {
$rc = new ReflectionClass($controller_name);
} catch (Exception $ex) {
if($segement == "") {
echo base_url(); die;
//header("Location:".$controller_name.'/overview');
//redirect($controller_name.'/overview');
//exit;
}
}
};
This won't work because base_url() gets initialized if a Controller is loaded.
And pre_controller basically means the opposite.
There are two options for you
Option 1
create a PreControllerHook.php in your application/hooks/ directory.
class PreControllerHook extends CI_Controller
{
public function initialize()
{
$controller_name = $this->router->fetch_class();
//... and so on
}
}
Setup your hooks.php config
$hook['pre_controller'] = [
[
'class' => 'PreControllerHook',
'function' => 'initialize',
'filename' => 'PreControllerHook.php',
'filepath' => 'hooks'
[
];
Option 2
create a PostControllerConstructorHook.php in your application/hooks/ directory.
class PostControllerConstructorHook
{
public function initialize()
{
$ci = get_instance();
$controller_name = $ci->router->fetch_class();
//... and so on
}
}
Setup your hooks.php config
$hook['post_controller_constructor'] = [
[
'class' => 'PostControllerConstructorHook',
'function' => 'initialize',
'filename' => 'PostControllerConstructorHook.php',
'filepath' => 'hooks'
[
];
You can find more information on their official documentation page here.
i hope this will work for you
base_url() function not working in codeigniter

Codeigniter redirect method is not working

This is my User.php controller
I am unable to use redirect method.
i am working on xampp localhost
?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->library('Admin_layout');
$this->config->load('reg_rules');
$this->load->model('admin/user_model');
$this->load->helper('form');
$this->load->helper('url');
}
public function index()
{
if (!$this->auth->loggedin()) {
redirect('admin/login');
}
}
public function add(){
//if($this->input->post('submit')){
$this->form_validation->set_rules($this->config->item('reg_settings'));
$data["reg_attrib"] = $this->config->item("reg_attribute");
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run('submit') == FALSE)
{
// templating
$this->admin_layout->set_title('Add a User');
$this->admin_layout->view('admin/add_user',$data["reg_attrib"]);
// templating
}
else
{
// Develop the array of post data and send to the model.
$passw = $this->input->post('password');
$hashpassword = $this->hash($passw);
$user_data = array(
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('contact_no'),
'email' => $this->input->post('email'),
'password' => $this->hash($hashpassword),
'doj' => time(),
);
$user_id = $this->user_model->create_user($user_data);
Here i am setting my success message using set_flashdata
and redirecting
if($user_id){
$this->session->set_flashdata('item', 'Record created successfully');
$this->redirect('admin/user/add','refresh');
}else{
echo "User Registration Failed!";
}
}//else
//} // submit
} // add
}
View_users.php
<?php
if($this->session->flashdata('item'))
{
echo $message = $this->session->flashdata('item');
}
?>
I am getting the following error
Fatal error: Call to undefined method User::redirect() in C:\xampp\htdocs\ci\application\controllers\admin\User.php on line 67
A PHP Error was encountered
Severity: Error
Message: Call to undefined method User::redirect()
Filename: admin/User.php
Line Number: 67
Backtrace:
Try to change from
$this->redirect('admin/user/add','refresh');
to
redirect('admin/user/add','refresh');
Hope it will be useful for you.

Trying to build the simplest codeigniter captcha according to the codeignuter help instructions but it dosen't work

Trying to build the simplest codeigniter captcha according to the codeigniter help instructions but it dosen't work.
My controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class c_captche extends CI_Controller {
//http://stackoverflow.com/questions/9484480/couldnt-connect-to-helper-in-codeigniter
//https://www.youtube.com/watch?v=TU_8b9SRe_k
//https://www.youtube.com/watch?v=tAmAxdSGZSs
/*
http://ellislab.com/codeigniter/user-guide/helpers/captcha_helper.html
https://www.youtube.com/watch?v=RR3ODc0vDvA
http://only4ututorials.blogspot.in/2014/04/how-to-create-captcha-with-codeigniter.html
http://www.cecilieo.com/techblog/how-to-use-codeigniter-captcha-plug-in/
*/
public function __construct()
{
parent::__construct();
$this->load->library('image_lib') ;
//$this->load->helper(array('captche'));
$this->load->helper('captcha');
}
public function index() {
echo "in c_captche";
$data = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => base_url().'application/captcha/',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$captch=create_captcha( $data);
print_r($captch);
$this->load->view('v_captche',$captch);
}
}
My view:
<?php
print_r($captch);
echo $captch ;
?>
I created folder called captcha under application folder.
No image been created there.
The error msg i get is:
PHP Error was encountered
Severity: Notice
Message: Undefined variable: captch
Filename: views/v_captche.php
Line Number: 8
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: captcha
Filename: views/v_captche.php
Line Number: 9
But even before the error msg, no img is been created in the folder.
As said in the documentation :
The "captcha" folder must be writable (666, or 777)
So check your folder rights, and you have to create this folder at your index.php root.
Then, for your view, you should use :
$this->load->view('v_captche',array('captcha' => $captch));
And in your view :
print_r($captcha);
echo $captcha['image'];

Getting a "Call to a member function function() on a non-object" error in code igniter [duplicate]

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm very new to CodeIgniter and not an expert in OOP so please bear with me.
This is the function I have in my model:
function get_company(int $user_id, $fields = '*'){
$r = $this->db->query("SELECT $fields FROM ".$this->db->dbprefix('companies')." WHERE user_id=?", $user_id)->row();
return $r;
}
function get_profile($user_id, $fields = '*'){
$r = $this->db->query("SELECT $fields FROM ".$this->db->dbprefix('users_profiles')." WHERE user_id=?", $user_id)->row();
return $r;
}
This is in my controller that is calling that model:
function index(){
$this->load->model('profiles_m');
$profile = $this->profiles_m->get_profile($this->access->getUid());
$company = $this->profile_m->get_company($this->access->getUid());
$vars = array(
'profile'=>$profile,
'company'=>$company,
);
$this->_getTemplate()->build('account', $vars);
}
An in my view:
$company = array(
'name' => 'company',
'id' => 'company',
'value' => "$company->name",
'class' => 'styl_f validate[required] text-input input-xlarge',
'placeholder' => "$company->name"
);
echo $company['value']
The error I am getting is this: Call to a member function get_company() on a non-object in C:\..\application\modules\accounts\controllers\accounts.php
I am under the impression that I am receiving these errors because I am passing a non object through get_company() but the thing that confuses me is that this error does not come up for get_profile(); The get_profile() function in my model is very similiar to my get_company() function. What is causing this error? How can I get rid of it?
The problem is within your controller:
function index(){
$this->load->model('profiles_m');
$profile = $this->profiles_m->get_profile($this->access->getUid());
$company = $this->profile_m->get_company($this->access->getUid()); // Right here
$vars = array(
'profile'=>$profile,
'company'=>$company,
);
$this->_getTemplate()->build('account', $vars);
}
The $profile variable uses $this->profiles_m as the object, but $company misses the letter 's' in the object.
Try with this line instead:
$company = $this->profiles_m->get_company($this->access->getUid());
You have a typo, the line should read:
$company = $this->profiles_m->get_company($this->access->getUid());
Notice 'profiles_m' and not 'profile_m'.
$company = $this->profile_m->get_company($this->access->getUid());
replace 'profile_m' to 'profiles_m'

Resources