How to use model function result in controller - php

I have an error in my controller. I am trying to use the result coming from model function to call another function in my model. I am using Codeigniter Framework. hope you can help me out. Thanks
Controller:
function photographer_campaign_details(){
$camp_id = $this->uri->segment(4);
$data['page_title'] = 'Photographer Campaign Details';
$adminId = $this->session->userdata('adminid');
$campaign = $this->Admin_model->get_all_photographer_campaign_details($camp_id);
$data['seller'] = $this->Admin_model->get_seller_name_by_id($campaign['uid']);//error is here: Undefined index: uid
$data['campaign'] = $campaign;
$this->load->view('admin/photographer_campaign_details',$data);
}
My Model:
function get_all_photographer_campaign_details($camp_id) {
$this->db->select('*');
$this->db->where('campaign_id',$camp_id);
$query = $this->db->get('ps_campaigns');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
return $data;
}
return array();
}
//get seller name by id
function get_seller_name_by_id($uid)
{
$this->db->select('firstname, lastname');
$this->db->where('id', $uid);
$query = $this->db->get('ps_users');
//return $query->row();
return $query->result_array();
}
an error is coming from the controller: Undefined index: uid

Looking at your get_all_photographer_campaign_details, if no rows are found then you return an empty array.
In your controller, you never check to see if a valid entry was found. As a result you get your undefined index: uid when an id is referenced in the URL that doesn't correspond to an entry, because $campaign is empty and doesn't have a uid key. Try something like this:
function photographer_campaign_details(){
$camp_id = $this->uri->segment(4);
$data['page_title'] = 'Photographer Campaign Details';
$adminId = $this->session->userdata('adminid');
$campaign = $this->Admin_model->get_all_photographer_campaign_details($camp_id);
if (!$campaign ){
show_404();
}
$data['seller'] = $this->Admin_model->get_seller_name_by_id($campaign['uid']);//error is here: Undefined index: uid
$data['campaign'] = $campaign;
$this->load->view('admin/photographer_campaign_details',$data);
}
Additionally, you are returning data wrong in the event that you do find data. Namely this bit in get_all_photographer_campaign_details:
foreach ($query->result_array() as $row) {
$data[] = $row;
}
Should be something like:
foreach ($query->result_array() as $row) {
$data = $row;
break;
}
The problem is that you are appending the row as one row in $data, but your controller is expecting to get the actual data itself. I.e. your controller is expecting this:
[
'campaignid' => 1,
'uid' => 'ijerjeire'
]
But you are returning this:
[
[
'campaignid' => 1,
'uid' => 'ijerjeire'
]
]
Note the extra array that everything is wrapped around. Basically, your model is returning an array of results, when your controller is just expecting results. My above suggestion will work if there is only ever supposed to be one campaign returned. If that is not the case, then you need to adjust your controller instead of your model method.
To reiterate my other point: make sure and validate the user input that comes from the URL. Otherwise you will return PHP errors instead of 404's.

Related

i want to display value from database in codeigniter but i am getting errror

I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
controller:
public function trainer($id)
{
$user_record = $this->db->query("select * from usr_data where usr_id=$id")->result();
$data['title'] = 'trainer Dashboard';
$data['user_record'] = null;
$data['active_courses'] = [];
$data['inprogress'] = [];
if(count($user_record)) {
$user_record = $user_record[0];
$data['title'] = ucwords($user_record->firstname).' Dashboard';
$data['user_record'] = $user_record;
$active_courses = $this->base_model->getTrainercourseAll($id);
$data['active_courses'] = $active_courses;
$inprogress = $this->base_model->getstaffinprogress($id);
$data['inprogress'] = $inprogress;
}
$this->load->view('trainer-dashboard', $data);
}
model:
public function getstaffinprogress($user_id) {
$result=$this->executeSelectQuery("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
return $result;
}
view:
<h3>Avg inprogress:<?php echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";?></h3>
I want to display the column percentage which is coming from database.above code is in the controller, model and view.i thought my controller code is wrong.
Anyone help me to get rid of this error. I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
Try this in your view file,
if(isset($inprogress)){
echo $inprogress->percentage;
}
Then your code look like this,
<h3>Avg inprogress:<?php if(isset($inprogress)){ echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";}?></h3>
Then call the controller function. I think inprogress is not set at the first time.
If it doesn't work, try to var_dump($inprogress) in controller and check value and type.
And try this code in your model. Query also seems not correct
public function getstaffinprogress($user_id) {
$this->db->select_avg('ut_lp_marks.percentage');
$this->db->where('ut_lp_marks.obj_id', $user_id);
$this->db->where('object_data.type', 'crs');
$this->db->where('ut_lp_marks.status', 1);
$this->db->join('object_data', 'object_data.obj_id = ut_lp_marks.obj_id');
$query = $this->db->get('ut_lp_marks');
return $query->result_array();
}
I assume that your db is ut_lp_marks. Then var_dump array and check data is correct first. Then access array element.
public function getstaffinprogress($user_id) {
$result = array();
$query=$this->db->query("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
foreach($query->result() as $row){
$result = $row;
}
return $result;
}
Also check $inprogress->percentage exists before print in view.

generating querying result for row() in codeigniter:

I am newbie in codeigniter. If I have a model like this :
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->row();
}
And I try to accessed it from may controller :
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
How to Generating Query Results, thanks for the help.
EDIT
I am new in CI, my question is : let's say I want to get the 'nama_user' into an a variable like this :
foreach ($data as $d) {
$name = $d['nama_user'];
}
echo json_encode($name);
I use firebug, it gives me null. I think my foreach is in a problem
In order to return an array from your model call you can use result_array() as
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->result_array();//<---- This'll always return you set of an array
}
Controller File with your query code
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
//Generating Query Results like this because you use $query->row();
$data->nama_user;
$data->keluhan;
$data->email;
$data->addresed_to;
$info_json = array("nama_user" => $data->nama_user, "keluhan" => $data->keluhan, "email" => $data->email, "addresed_to" => $data->addresed_to);
echo json_encode($info_json);
}
MODEL.PHP
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->row_array();
}
//Generating Query Results if use $query->row_array(); in model file
Controller.php
function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
foreach($data as $row)
{
$myArray[] = $row;
}
echo json_encode($myArray);
You fetched data for selected id it means you get a single row, if you want to get "nama_user" then in your controller:
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
$name = $data->nama_user;
echo json_encode($name);
}

CodeIgniter $data not passed from Controller to View

my controller is not passing $data to my view and I don't know why not. I'm reusing code from a previous project which worked fine and I certainly understand the idea of how $data passing is meant to work. But maybe I missed something when copying code over?
I put in the variable $data['hello'] in there just for testing purposes. As you can see from the output $hello isn't even getting through. The if fails and the else code is run correctly which means the view file itself is being loaded.
Controller:
function users() {
$data['title'] = 'users';
$data['users'] = $this->main_m->get_users();
$data['hello'] = 5;
$this->load->view('users', $data);
}
View:
<?php
echo $hello;
if ($users->num_rows != 0) {
foreach ($users->result() as $user) {
}
} else {
echo "No users.";
}
Output (abridged):
A PHP Error was encountered
Message: Undefined variable: hello
Line Number: 2
A PHP Error was encountered
Message: Undefined variable: users
Line Number: 3
A PHP Error was encountered
Message: Trying to get property of non-object
Line Number: 3
No users.
Edit: more info on request:
Model:
public function get_users($amount = 0, $offset = 0) {
$this->db->from('users');
$this->db->order_by('l_name', 'desc');
if ($amount != 0)
$this->db->limit($amount, $offset);
return $this->db->get();
}
I always do like this
change your model to
$query = $this->db->get();
return $query->result();
And in view
if (count($users)> 0) {
foreach ($users as $user) {
echo $user['name'];
}
} else {
echo "No users.";
}
Hope this helps
Regards
iijb
Just write $data = array(); before you are sending some data into $data array.
function users() {
$data = array();
$data['title'] = 'users';
$data['users'] = $this->main_m->get_users();
$data['hello'] = 5;
$this->load->view('users', $data);
}
I think you could solve your issue with some simple var_dump() checks.
Check what's coming out of your model by var_dump()ing $data['users'] - is this an object? What happens when you var_dump() $data['users']->result()?
Then, var_dump() $data in your view - does it have all the pieces?
Thing is, even showing us your model function doesn't prove that your getting a real data result. Check that. Your code looks okay at a glance so I don't think that is where the issue exists.
There is something very basic that is wrong. So get out of that controller and do a sanity check. First confirm that your welcome view is working. If it is go to the welcome controller and put this in the index method
$data['here'] = 'we are here' ;
$this->load->view('welcome_message', $data);
and then somewhere in the welcome.php view file
<?php echo $here ?>
You do not need to set this: $data = array();
However some people suggest it because that way even if you dont create any data variables you wont get an error if its in the view call $this->load->view('welcome_message', $data);
finally i would suggest looking at this
function users() {
$data['title'] = 'users';
$data['users'] = $this->main_m->get_users();
$data['hello'] = 5;
$this->load->view('users', $data);
}
lets see you have method called users, returning an object called users, and a view called users -- that could get confusing ! :-)

Returning NULL from query for datatables

I'm wondering what would be best to do. Right now I have running a query to see if I have any results returned and if none are returned I return NULL.
On my controller I send that resultset whether it be an object or NULL to my table and it echos the rows on the view page.
For my tables I am using the jquery datatables plugin. I'm trying to figure out how I can have it handle the data when the sent value is NULL that way it doesn't show me an error when it hits my foreach loop.
Controller:
$news_articles = $this->news_model->get_news_articles();
$this->data['news_articles'] = $news_articles;
Model:
/**
* Get news articles
*
* #return object
*/
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return NULL;
}
View:
$tmpl = array ( 'table_open' => '<table class="table" id="newsarticles-table">' );
$data = array('name' => 'newsarticles', 'class' => 'selectall');
$this->table->set_heading(form_checkbox($data), 'ID', 'Date', 'Title');
$this->table->set_template($tmpl);
foreach ($news_articles as $row)
{
$checkbox_data = array(
'name' => 'newsarticles',
'id' => $row->id
);
$this->table->add_row(form_checkbox($checkbox_data), $row->id, $row->date_posted, $row->article_title);
}
echo $this->table->generate();
I typically respond using JSON and then add a "success" type boolean and then check that value before trying to process any data. It also allows for an easy way to place an error message in the response if something goes wrong.
Just another idea
Model
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return FALSE;
}
Controller
$news_articles = $this->news_model->get_news_articles();
if(!$news_articles) $this->data['success'] = FALSE;
else
{
$this->data['news_articles'] = $news_articles;
$this->data['success'] = TRUE;
}
In the view
if($success)
{
foreach ($news_articles as $row)
{
//....
}
}
else echo "No results found !";
Just return an empty array from the model, if there are not results. That way your foreach won't break. It just won't loop over anything.

Codeigniter generating html table (Trying to get property of none object)

I am trying to generate a table to display my websites enquiries and add a column containing links(actions) for each of the enquiries.
Upon creating my table I am receiving the following error:
Message: Trying to get property of non-object (line 55)
My controller is as follows:
$this->table->set_heading('ID', 'Name', 'Surname', 'Email', 'Phone','Message','Date','Actions');
$enquiries = $this->contact_model->get_table_enquiries($per_page,$offset);
foreach($enquiries as $row) {
$links = anchor('admin/enquiries/edit/' ,'Edit');
$links .= anchor('admin/enquiries/delete/', 'Delete');
$this->table->add_row(
$row->id, //line 55
$row->first_name,
$row->last_name,
$row->email_address,
$row->phone_number,
$row->message,
$links
);
}
$viewdata['enquiries_table'] = $this->table->generate();
And the function in the model that gets the results:
function get_table_enquiries($per_page,$offset)
{
$this->db->order_by('date','desc');
$query=$this->db->get('contact',$per_page,$offset);
return $query;
}
How can I get my foreach loop to work and create the necessary rows and append the links???
Why am I receiving the error message?
I think you need to try
foreach ($enquiries->result() as $row)
function get_table_enquiries($per_page,$offset)
{
$this->db->order_by('date','desc');
$query=$this->db->get('contact',$per_page,$offset);
return $query->result(); //do this
}

Categories