Call to a member function on a non-object php ci - php

Excuse me master, I had an error in my controller, I'm a newbie PHP CI programmer.
Can you help me where is my mistake on this code? The error says : "Call to a member function produk_list() on a non-object"
And here's my code on my controller :
function index()
{
$data = array();
$data['template'] = 'produk/index';
$data['query'] = $this->produk_model->produk_list($this->uri->segment(4),5,true);
$data['page_title'] = 'Produk';
$this->pagination->initialize(paging_admin($this->produk_model->count(true),'admin/produk/index'));
$data['pagination'] = $this->pagination->create_links();
$data['breadcrum'] = array(array("MIS Admin Panel",'admin'),
array('Produk','admin/produk'),
array('List','')
);
$data = array_merge($data,admin_info());
$this->parser->parse('admin/index',$data);
}
And here's my code on my models (produk_model)
function produk_list($limit,$offset,$admin = false)
{
if($admin === false) $this->db->select('id,title,image,content,created_at');
if($admin === false) $this->db->where('publish',1);
$this->db->order_by('id','DESC');
($limit == '')? $this->db->limit($offset,0) : $this->db->limit($offset,$limit);
$query = $this->db->get('produk');
if($admin === false){
$data = array();
foreach($query->result() as $row){
$data[] = array('produkid' => $row->id,
'produktitle' => $row->title,
'produkurltitle' => url_title($row->title,'dash',true),
'produkdate' => human_date_time($row->created_at),
'produkfrontdate' => human_date($row->created_at),
'produkimage' => ($row->image != '')? '<img src="{produk_tpath}'.$row->image.'" alt="'.$row->title.'" title="'.$row->title.'" />' : '',
'produkcontent' => character_limiter(strip_tags($row->content),200),
);
}
return $data;
}else{
return $query->result();
}
}
Thank you master...
Hope you can help me...

You must either load the model in your controller or autoload the model in autoload.php under config before calling the model function
$this->load->model('produk_model');

Related

Codeigniter: Call to a member function result_array() on a non-object caused by bad column?

I'm having an issue in codeigniter to return a result set. When I'm avoiding 1 column in my select, the result is correct.
But when i want to include the column (description) then i get the error and my result-set is corrupt. Anyone knows how to solve this issue. The column has soms records with characters like &,'/... I might think that this causes the problem.
some details:
'char_set' => 'UTF-8',
'dbcollat' => 'Latin1_General_100_CS_AS',
I already tried to change these parameters without success.
EDIT Code added:
get and get_by function.
public function get($id = NULL, $single = FALSE) {
if($id != NULL){
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE){
$method = 'row';
}
else{
$method = 'result';
}
if($_order_by != ''){
if(!count($this->db->ar_orderby)){
$this->db->order_by($this->_order_by);
}
}
//$query = $this->db->query("Select Description from items WHERE Company = 'MINITFR'");
// $array = $query->result_array();
// return 'test';
// var_dump($this->db->get_compiled_select($this->_table_name));
return $this->db->get($this->_table_name)->result_array();
// return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE) {
$this->db->where($where);
return $this->get(NULL,$single);
}
function in controller:
public function show_items(){
$this->load->model('item_m');
$this->data['ajax_req'] = TRUE;
$where = "Company = '".$this->session->userdata('company')."'";
$this->data['item_list'] = $this->item_m->get_by($where,FALSE);
$this->load->view('pages/details/components/item_list', $this->data);
}
use this one:
return $this->db->get('table_name')->result_array();

how to write a function for fetching the record by sending only parameters in codeigniter?

I have 100 tables or can be more than that,I always need to fetch the record all the time in my application from various table.So writing functions for each and every query its not good coding standard.
$this->db->select();
$this->db->from("table1");
$query = $this->db->get();
return $query->result_array();
$this->db->select();
$this->db->from("table2");
$query = $this->db->get();
return $query->result_array();
$this->db->select();
$this->db->from("table1");
$this->db->where("id",10);
$query = $this->db->get();
return $query->result_array();
I want the good coding standard for this.
Write this code in controller.
$data = $this->common_model->getRecords("table_name", "*", array("field1" => $this->input->post('user_name')));
This will be your function in model (that is common_model).
public function getRecords($table, $fields = '', $condition = '', $order_by = '', $limit = '', $debug = 0) {
$str_sql = '';
if (is_array($fields)) { #$fields passed as array
$str_sql.=implode(",", $fields);
} elseif ($fields != "") { #$fields passed as string
$str_sql .= $fields;
} else {
$str_sql .= '*'; #$fields passed blank
}
$this->db->select($str_sql, FALSE);
if (is_array($condition)) { #$condition passed as array
if (count($condition) > 0) {
foreach ($condition as $field_name => $field_value) {
if ($field_name != '' && $field_value != '') {
$this->db->where($field_name, $field_value);
}
}
}
} else if ($condition != "") { #$condition passed as string
$this->db->where($condition);
}
if ($limit != "")
$this->db->limit($limit);#limit is not blank
if (is_array($order_by)) {
$this->db->order_by($order_by[0], $order_by[1]); #$order_by is not blank
} else if ($order_by != "") {
$this->db->order_by($order_by); #$order_by is not blank
}
$this->db->from($table); #getting record from table name passed
$query = $this->db->get();
if ($debug) {
die($this->db->last_query());
}
$error = $this->db->_error_message();
$error_number = $this->db->_error_number();
if ($error) {
$controller = $this->router->fetch_class();
$method = $this->router->fetch_method();
$error_details = array(
'error_name' => $error,
'error_number' => $error_number,
'model_name' => 'common_model',
'model_method_name' => 'getRecords',
'controller_name' => $controller,
'controller_method_name' => $method
);
$this->common_model->errorSendEmail($error_details);
redirect(base_url() . 'page-not-found');
}
return $query->result_array();
}
I used this code for fetching the record. you just need to pass the table name ,fields name ,the condition and limit.
your codes can actually be in 1 line
$query= $this->db->get('table1')->result_array();
$query= $this->db->get_where('table1', array('id'=>3,'name'=>'tom'))->result_array();
or if you really want a function
function getData($table){
$query=$this->db->get($table)->result_array();
return $query;
}
$data= getData('table1');

Codeigniter: Validate form field on edit

I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');

Add or edit data if already exist in database

Im trying to add or edit data depending if its already stored in the database. As you can see below im checking if user already exist with getuserid($id) loading the corresponding view but the problem is when i trigger add_user() or edit_user() as none of these methods are redirecting back as it should be. Any suggestions? This is the complete code http://pastebin.com/2G7D8ie4
public function getuserid($id = NULL){
if(!$id)
{
show_404();
}
$query = $this->Users_model->getuserid($id);
if($query == false){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id);
}else{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
$this->load->view('themes/'.$this->config->item('theme_front').'.php', $data);
}
Model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
can you try making your model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
$result=array();
foreach ($query->result() as $rows){
$result[]=$rows;
}
return $result;
}
and controller
if(count($query)>0){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
else
{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id
);
}

Sending two data arrays to view from controller in codeigniter

I want to send two data arrays from my controller to view how can I do it ?
Following is my controller code
class Home extends CI_Controller {
public function box() {
$url = $this->pageURL();
$id_from_url = explode('/', $url);
$id = $id_from_url[6];
$query = $this->db->get_where('mc_boxes', array('idmc_boxes' => $id));
$row = $query->row();
$rowcount = $query->num_rows();
if ($rowcount <= 0) {
echo 'ID not found';
} else {
$box_id = $row->idmc_boxes;
$customer_id = $row->customers_idcustomers;
$language_id = $row->languages_idlanguages;
$template_id = $this->getTemplateID($box_id);
$template_data = $this->getTemplateData($template_id);
$variables_data = $this->getVariables($customer_id, $language_id);
$title = $variables_data[0]['value'];
$this->load->view('template', $template_data);
}
}
}
In my template view when I echo $title it says it is undefined
how can I send the whole $variables_data array with $template_data array
Thanks :)
Instead of using each array ,all do set to one
Like that,giving important sections only
...................
$data['template_data'] = $this->getTemplateData($template_id);
$data['variables_data'] = $this->getVariables($customer_id, $language_id);
$data['title'] = $variables_data[0]['value'];
$this->load->view('template', $data);
you can take $template_data and $variables_data in view files
Generally you pass in data as:
$data['template_data'] = $template_data;
$data['title'] = $$title;
....
$this->load->view('template', $data);

Categories