call to undefined method CI_Input::load_query() - php

i am using codeigniter 3.0.4 framework. i have extended the input class named as MY_input.php. i have placed this file on inside the application/core folder. This is working fine on my localhost xampp server. But i am getting this error call to undefined method CI_Input::load_query() when i deploy my project folder on a live server. i have uploaded the files correctly and i have MY_input.php in application/core folder on the live server as well.
i am still running it successfully on my localhost but can't do so on live. i am pasting the relevant code here. Inside Login_controller i have
function displaySorted($query_id = 0,$sortBy = 'DeviceName',$sortOrder = 'asc',$offset=0)
{
$dataS = $this->session->userdata('logged_in');
if(isset($dataS))
{
$limit = 20;
$data['offset'] = $this->uri->segment(6);
$data['query_id']=$query_id;
$data['fields'] = array(
'ID' => 'ID',
'DeviceType' => 'Device Type',
'RegistrationDateTime' => 'RegistrationDateTime',
'LastUpdateDateTime' => 'LastUpdateDateTime',
'LastPushNotificationSent' => 'LastPushNotificationSent',
'DeviceName' => 'Device Name',
'Latitude' => 'Latitude',
'Longitude' => 'Longitude',
'CityName' => 'CityName',
'StateName' => 'StateName',
'CountryName' => 'CountryName',
'AppVersion' => 'AppVersion',
'iOSVersion' => 'iOSVersion',
'IPAddress' => 'IPAddress',
'TotalCities' => 'TotalCities',
'DeviceDID' => 'DeviceDID',
'DeviceToken'=> 'DeviceToken',
'DeviceLanguageID'=> 'DeviceLanguageID',
'LocationID' => 'LocationID',
'TempScale' => 'TempScale',
'IsFreezeAlertEnabled' => 'IsFreezeAlertEnabled',
'ShouldShowTempOnBadge' => 'ShouldShowTempOnBadge',
'ShowNegativeAsPositive' => 'ShowNegativeAsPositive',
'LastTempC' => 'LastTempC',
'LastTempF' => 'LastTempF',
'IsDeviceUsingProdCert' => 'IsDeviceUsingProdCert'
);
$this->input->load_query($query_id);
$query_array = array(
'DeviceName' => $this->input->get('DeviceName'),
'RegistrationDateTime' => $this->input->get('RegistrationDateTime'),
'LastUpdateDateTime' => $this->input->get('LastUpdateDateTime'),
'AppVersion' => $this->input->get('AppVersion'),
'iOSVersion' => $this->input->get('iOSVersion'),
'DeviceDID' => $this->input->get('DeviceDID'),
'DeviceToken' => $this->input->get('DeviceToken')
);
$results = $this->user_model->searchSorted($query_array,$limit, $offset, $sortBy, $sortOrder);
$data['tableInfo'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
$data['DeviceName'] =$query_array['DeviceName']; $data['RegistrationDateTime']=$query_array['RegistrationDateTime'];
$data['LastUpdateDateTime']=$query_array['LastUpdateDateTime'];
$data['AppVersion']=$query_array['AppVersion'];
$data['iOSVersion']=$query_array['iOSVersion'];
$data['DeviceDID']=$query_array['DeviceDID'];
$data['DeviceToken']=$query_array['DeviceToken'];
//pagination functionality
$config['base_url'] = site_url("login_controller/displaySorted/$query_id/$sortBy/$sortOrder");
$config['per_page'] = $limit;
$config['total_rows'] = $data['num_results'];
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$data['sortBy'] = $sortBy;
$data['sortOrder'] = $sortOrder;
$this->load->view('adminPanel_view', $data);
}
else
{
//echo $this->;exit;
redirect('login_controller');
}
}
Now MY_input.php contains this code:
class MY_input extends CI_Input
{
public function __construct()
{
parent::__construct();
}
public function save_query($query_array)
{
$CI =&get_instance();
$CI->db->insert('ci_query',array('query_string'=> http_build_query($query_array)));
return $CI->db->insert_id();
}
public function load_query($query_id)
{
$CI =&get_instance();
$rows = $CI->db->get_where('ci_query', array('id' => $query_id))->result();
if (isset($rows[0]))
{
parse_str($rows[0]->query_string, $_GET);
}
}
[![enter image description here][1]][1]}
Now the error is not inside the code but i am placing MY_input.php file. But i don't know what to do and how to solve this issue plus i don't want to change the core framework files of codeigniter.

I think you should use the right camel case file name: MY_Input.php
and class name:
class MY_Input extends CI_Input {
(please notice: the I letter is uppercase)
see documentation:
http://www.codeigniter.com/user_guide/general/core_classes.html

Related

How to use parameter in function with pagination CodeIgniter?

I have function which takes state name as a parameter and displays all the cities of that specific state. Since list of cities is very long I have used pagination in the same function but when I click on the 'Next' or any other pagination link the function accepts the offset value in the $state variable. The function is
public function load_Page($state){
$this->load->database();
$this->load->library('pagination');
$a = 1;
$this->db->select("*")->where("userstate" , $a)->where("state" , $state);
$query0 = $this->db->get("city");
$this->db->select("*")->where("userstate" , $a)->where("state" , $state);
$query1 = $this->db->get('city' , 10 , $this->uri->segment(3));
$config["base_url"] = base_url()."index.php/city/load_Page";
$total_row = $query0->num_rows();
$config['page_query_string'] = TRUE;
$config["total_rows"] = $total_row;
$config["per_page"] = 10;
$this->pagination->initialize($config);
$data["state"] = $state;
$data["result"] = $query1->result();
//$data["rows"] = $query1->num_rows();
$this->load->view('header');
$this->load->view('city', $data);
$this->load->view('footer');
}
Is there any other way out to do it or I am going completely wrong?
First of all, when you are paginating, the page number has to come from the URL, and that's always available as a parameter in the controller method. It should default to page 1.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class City extends CI_Controller {
public function load_page( $state, $page = 1 ){
// I'm going to use an alias for this model
$this->load->model('example_model', 'model');
// Use the URL helper for site_url()
$this->load->helper('url');
// Set pagination config
$config['pagination_settings'] = [
'per_page' => 10,
'use_page_numbers' => TRUE,
'uri_segment' => 4, // This is very important!!!
'base_url' => site_url('city/load_page/' . $state)
];
// Get the total rows
$config['pagination_settings']["total_rows"] = $this->model->pagination_count( $state );
// Load and initialize pagination
$this->load->library('pagination');
$this->pagination->initialize($config['pagination_settings']);
$data = [
'state' => $state,
'rows' => $this->model->get_cities( $state, $page, $config['pagination_settings']['per_page'] ),
'links' => $this->pagination->create_links()
];
// Use data in views or wherever needed ...
$this->load->view('city', $data);
}
/**
* Create the rows to paginate
*/
public function setup()
{
// I'm going to use an alias for this model
$this->load->model('example_model', 'model');
$this->model->setup();
}
// -----------------------------------------------------------------------
}
Next, you should move your database queries to a model. You don't need to use transactions for your 2 select type queries.
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Example_model extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function pagination_count( $state )
{
return $this->db->where("state" , $state)
->count_all_results('city');
}
public function get_cities( $state, $page, $limit )
{
$offset = ( $page * $limit ) - $limit;
$query = $this->db->where("state" , $state)
->limit( $limit, $offset )
->get('city');
if( $query->num_rows() > 0 )
return $query->result();
return NULL;
}
/**
* Setup for testing
*/
public function setup()
{
$this->load->dbforge();
$fields = array(
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'state' => array(
'type' => 'VARCHAR',
'constraint' => '32',
),
'city' => array(
'type' => 'VARCHAR',
'constraint' => '32',
),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('city', TRUE);
for( $x = 1; $x <= 40; $x++ )
{
$this->db->insert('city', array(
'state' => 'ca',
'city' => 'x' . $x
));
}
}
}
This is the view that I used:
<?php
echo '<h1>' . $state . '</h1>';
echo $links . '<br /><br />';
foreach( $rows as $row )
{
echo $row->city . '<br />';
}
To set up the database for testing, I went to:
http://localhost/index.php/city/setup
Then to check out that the pagination works, I went to:
http://localhost/index.php/city/load_page/ca
It should work for you, as this code is now fully tested.
UPDATE --------------------
If you want to add more parameters to your pagination, do it with query strings. You will need to set the pagination config with this extra setting:
$config['pagination_settings']['reuse_query_string'] = TRUE;
That means the config would look like this:
$config['pagination_settings'] = [
'per_page' => 10,
'use_page_numbers' => TRUE,
'uri_segment' => 4, // This is very important!!!
'base_url' => site_url('city/load_page/' . $state),
'reuse_query_string' => TRUE
];
And then you create the link to the first page with your params:
http://localhost/index.php/city/load_page/ca?a=1&b=2&c=3
And because of the reuse_query_strings being set to TRUE, that means that ?a=1&b=2&c=3 would all be attached to the pagination links.

Error Fatal error: Call to a member function insert() on a non-object

I'm using a callback after inserting in the database, to pass values to this other table, i think the method i used its fine. But it gives me this error when its inserting to the other table in the database, probably in my model, or something in the controller im kind of clueless in this error, can someone please help me.
Before someone say its to put $this->load->database(); its already in my autoload in config file :)
Fatal error: Call to a member function insert() on a non-object
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Finances::$inventory_model
Filename: controllers/finances.php
Line Number: 125
CONTROLLER:
public function inventory_management($post_array,$primary_key)
{
$this->load->model('inventory_model');
if($post_array['id_expense']!=null){
$type = 'add';
$id_exp_detail = $primary_key;
$result = $this->inventory_model->insert([
'id_exp_detail' => $id_exp_detail,
'name' => $post_array['brand'],
'quantity' => $post_array['item_quantity'],
'lote' => $post_array['package_code'];
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}else if ($post_array['name']!=null){
$type = 'sub';
$id_treatment = $primary_key;
$result = $this->inventory_model->insert([
'id_treatment' => $id_treatment,
'name' => $post_array['name'],
'quantity' => $post_data['recomended_dose'],
'lote' => $post_array['id_package'],
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}else{
$type = 'sub';
$id_fertilization = $primary_key;
$result = $this->inventory_model->insert([
'id_fertilization' => $id_fertilization,
'name' => $post_data['name'],
'quantity' => $post_data['quantity'],
'lote' => $post_data['id_package'],
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}
if($result){
echo "validation Complete";
}
}
MODEL
class CRUD_model extends CI_Model
{
protected $_table = null;
protected $_primary_key = null;
// ------------------------------------------------------------------------
public function __construct()
{
parent::__construct();
}
public function insert($data)
{
$this->db->insert($this->_table, $data);
// return $this->db->insert_id();
}
MODEL:
class inventory_model extends CRUD_model
{
protected $_table = 'inventory_management';
protected $_primary_key = 'id';
// ------------------------------------------------------------------------
public function __construct()
{
parent::__construct();
}
// ------------------------------------------------------------------------
}
here is the wrong you call wrong model file
$this->load->model('inventory_model');
it should be
$this->load->model('crud_model');
and you use wrong way to pass array in function
$param = array('id_exp_detail' => $id_exp_detail, 'name' => $post_array['brand'], 'quantity' => $post_array['item_quantity'], 'lote' => $post_array['package_code'], 'type' => $type, 'date' => date(), 'id_user' => $this->session->userdata('id_user'), 'id_entity' => $this->session->userdata('id_entity'));
$result = $this->inventory_model->insert($param);

Creating REST API with CakePHP

I have to create a REST API for mobile backend using CakePHP. After following the instructions here I have been able to setup the requirements for creating a REST API. The problem is that I am getting a null in my output when I use the _serialize variable. Here is my code:
class InvitationController extends AppController {
public $components = array('RequestHandler');
public function index() {
}
public function add() {
if ($this->request->is('post')) {
$this->loadModel('Organizer');
$numPeople = $this->request->data['numpeople'];
$share = $this->request->data['myshare'];
$organizer = $this->request->data['organizer'];
$organizerMobile = $this->request->data['organizermobile'];
$this->set('organizerMobile', $organizerMobile);
$deadline = $this->request->data['deadline'];
$links = array();
date_default_timezone_set("Asia/Calcutta");
$now = date('Y-m-d');
$lastOrganizer = $this->Organizer->find('first', array(
'order' => array('Organizer.id' => 'desc')
));
$checkOrganizer = $this->getOrganizerDetails($lastOrganizer);
$pass = //something;
// save data in organizers table
$this->organizer->create();
$this->organizer->save(
array(
'name' => $organizer,
'mobile' => $organizerMobile,
'p_id' => 1,
'share' => $share,
'deadline' => $deadline,
'password' => $pass,
'group_cardinality' => $numPeople,
'created_on' => $now,
)
);
$message = 1;
$this->set(array(
'message' => $message,
'_serialize' => array($message)
));
}
}
}
When I make a request to POST /invitation.json I get null in the ouput with status 200. On the other hand if I simply do echo json_encode($message) in the Controller or in the View I get the correct output. I think I am doing something wrong. Please help!
That's wrong:
'_serialize' => array($message)
Pay attention to the manual, it shows it correctly in the provided examples.
'_serialize' => array('message')

Cakephp AuthComponent: Login successfull despite wrong password

I'm running a 2.2.2 CakePHP Application, everything works as desired. Now I'm developing a Android App for it and therefore need to create the interfaces between those two apps. That's why I need to login users manually. So I created a whole new controller, the AndroidController, in order to bundle everything at one place. First thing to do would be the Login-Action. So I setup the following controller:
<?php
App::uses('AppController', 'Controller');
/**
* Android Controller
*
* #package app.Controller
*/
class AndroidController extends AppController {
public $components = array('RequestHandler','Auth');
public $uses = array('User');
public function beforeFilter() {
$this->Auth->allow();
}
public function login() {
//For testing purposes
$postarray = array('_method' => 'POST','data' => array('User' => array('email' => 'user#gmail.com', 'password' => 'THISisDEFINITELYaWRONGpassword')));
$id = $this->tryToGetUserID($postarray['data']['User']['email']);
if($id == 0){
//return Error json, unknown User
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 1,
'error_msg' => 'Unknown User'
));
}else{
// if ($this->request->is('post')) {
$postarray['data']['User'] = array_merge($postarray['data']['User'], array('id' => $id));
$this->User->id = $id;
if ( $this->Auth->login($postarray['data']['User'])) {
// Login successfull
$this->User->saveField('lastlogin', date(DATE_ATOM));
$user = $this->User->find('all', array(
'recursive' => 0, //int
'conditions' => array('User.id' => $id)
));
$loggedInUser = array(
'tag' => 'login',
'success' => 1,
'error' => 0,
'uid' => '??',
'user' => array(
'name' => $user['0']['User']['forename'].' '.$user['0']['User']['surname'],
'email' => $user['0']['User']['email'],
'created_at' => $user['0']['User']['created'],
'updated_at' => $user['0']['User']['lastlogin']
)
);
$this->set('result', $loggedInUser);
} else {
// Login failed
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 2,
'error_msg' => 'Incorrect password!'
));
}
// }
}
}
public function tryToGetUserID($email = null) {
$user = $this->User->find('list', array(
'conditions' => array('User.email' => $email)
));
if(!empty($user)){
return array_keys($user)['0'];
}else{
return 0;
}
}
}
You need to know that this method will be called as a POST request, but for testing purposes I manually created a post-array. In future I will use the $_POST array.
So, what happens: The Login with a registered user works, but it works every time! Even though the password is wrong or missing! The program never reaches the part in code with the "Login failed" comment.
Am I missing something here..?
Thank you!
If you take a closer look at the documentation you will notice that AuthComponent::login() will ...
In 2.x $this->Auth->login($this->request->data) will log the user in with whatever data is posted

CodeIgniter - Can not run $this->input->post(‘inputName’); in Modular Extensions

As my title, I tried call that method but I got an error:
Fatal error: Call to a member function post() on a non-object in C:\xampp\htdocs\cifirst\application\modules\front\controllers\shopping.php on line 11
If I create a controller not in module, that method I can use very easy but in this case can not (everything code in method below can not run). This is my code:
public function add_to_cart() {
$data = array(
'id' => $this->input->post('productId'), // line 11
'name' => $this->input->post('productName'),
'price' => $this->input->post('productPrice'),
'qty' => 1,
'options' => array('img' => $this->input->post('productImg'))
);
$this->load->library('MY_Cart');
$this->cart->insert($data);
//redirect($_SERVER['HTTP_REFERER']);
//echo $_POST['productId'].'-'.$_POST['productName'];
}
And this code doesn't work too:
public function __construct() {
$this->load->library('cart');
$this->load->helper('form');
}
I'm using XAMPP 1.8.1, CodeIgniter 2.1.3 and newest MX. Please help me!
When you're using CodeIgniter functions outside of controllers, models, and views you need to get an instance of Codeigniter first.
class MyClass {
private $CI;
function __construct() {
$this->CI =& get_instance();
$this->CI->load->library('cart');
$this->CI->load->helper('form');
}
public function someFunction() {
$var = $this->CI->input->post("someField");
}
}
If you are calling:
$this->input->post('productId');
inside controller than the problem is with your constructor declaration or your class name
Your construct part should contain code like this:
Class Home extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->CI->load->library('cart');
$this->CI->load->helper('form');
}
public function add_to_cart()
{
$data = array(
'id' => $this->input->post('productId'), // line 11
'name' => $this->input->post('productName'),
'price' => $this->input->post('productPrice'),
'qty' => 1,
'options' => array('img' => $this->input->post('productImg'))
);
}
}
It will work fine if you are calling from helpers function or any other classes than you should do something like this:
function __construct()
{
parent::__construct();
$this->CI->load->library('cart');
$this->CI->load->helper('form');
$this->CI =& get_instance();
}
public function add_to_cart()
{
$data = array(
'id' => $this->CI->input->post('productId'), // line 11
'name' => $this->CI->input->post('productName'),
'price' => $this->CI->input->post('productPrice'),
'qty' => 1,
'options' => array('img' => $this->CI->input->post('productImg'))
);
}

Categories