CodeIgniter $data not passed from Controller to View - php

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 ! :-)

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.

Call to a member function insert() on null. Codeigniter

Hi everyone I am getting the following error when I submit my form for my CI 3 website:
Fatal error: Call to a member function insert() on null
This error is occurring on line 20 which is:
$query = $this->db->insert('temp_subscribed_users', $data);
Here is the full function:
public function add_temp_user($key)
{
echo "hello";
$data = array(
'TEMP_EMAIL' => $this->input->post('email'),
'TEMP_KEY' => $key
);
echo var_dump($data);
$query = $this->db->insert('temp_subscribed_users', $data);
if($query)
{
return true;
}else{
return false;
}
}
I am not sure what it means by null. The table name is correct and I did a var_dump to confirm that the array is being populated. I also made sure that I am getting into the function by echoing "hello" and it is outputting onto the page.
Any help is appreciated thank you!
Additional info: Running using XAMPP localhost.
load database and then call insert function. Codeigniter does not load database automatically for the performance issue.
$this->load->database();
$query = $this->db->insert('temp_subscribed_users', $data);
Well first of all you're not utilizing the MVC model of codeigniter. Controller is for functions, Model is for the database connections.
First autoload your database, If not just put it in the code. But here is how it should look like.
CONTROLLER FUNCTION
public function add_temp_user($key)
{
echo "hello";
$this->load->model('MY_MODEL');
//If you're not autoloading db include the next line
//$this->load->library('database');
$data = array(
'TEMP_EMAIL' => $this->input->post('email'),
'TEMP_KEY' => $key
);
echo var_dump($data);
//If you confirmed the data var dumped
$success = $this->MY_MODEL->insert_to_db($data);
if($success == true)
{
//Do something
}
else
{
//Do something
}
}
MODEL
public function insert_to_db($data)
{
$query = $this->db->insert('temp_subscribed_users', $data);
//
if($query)
{
return true;
}
else
{
return false;
}
}
Make sure the TEMP_EMAIL and TEMP_KEY are the columns in your database and temp_subscribed_users is your table name
Try to solve your problem by getting into the autoload.php in the config folder and add database on the array for libraries, like this: $autoload['libraries'] = array('database');
Please check whether object is created or not.
Check that object is available in that class

fatal error in OpenCart: call to undefined function error

I do not want to be asking a question that has already been answered, however I have done a ton of research and I am stuck. Any help would be appreciated.
I am trying to query and add database results to OpenCart's addproduct.tpl
In the MODEL file I have:
public function units() { //function that gets database info and returns it
$unit_variables = $this->db->query("SELECT unit FROM ". DB_PREFIX ."
weight_class_description");
if (!$unit_variables) {
die(mysql_error());
}
else {
foreach ($unit_variables->rows as $temp_var) {
print_r($temp_var['unit'], true);
}
}
}
In the CONTROLLER file I have:
$this->load->model('catalog/product'); //where my function is located
$this->model_catalog_product->units();
$weight_variables = units();
if (isset($this->request->post['weight_variables'])){
$this->data['weight_variables'] = $this->request->post['weight_variables'];
}
In the VIEW I have:
<?php echo $weight_variables ?>
I get the following error:
Call to undefined function units() in /path/to/controller/file on line etc.
Note: When I print_r($temp_var); instead of returning print_R($temp_var, true) and delete these lines of code $weight_variables = units(); if (isset($this->request->post['weight_variables'])){ $this->data['weight_variables'] = $this->request->post['weight_variables'] } in the controller file my model file will display the query results on the addproduct.tpl
units() is a METHOD of your object, yet you're calling it as a standalone regular function:
$weight_variables = units();
^^^^^^^
Shouldn't it be:
$weight_variables = $this->model_catalog_product->units();
instead? And note that as-written, your method doesn't actually return anything, so $weight_variables will simply get assigned null..

message undefined variable: news on view page

I'm new to PHP and CodeIgniter, and saw that there is many questions mentioning this and been trying them all but nothing seems to work. Everything is auto-loaded in configuration, the database is running and function for posting to database are working but writing to view page doesn't work at all. Except for displaying username, but for that I create a new variable on view page.
Controller
public function ShowNews()
{
$data = array();
$this->load->model('user');
$data['news'] = $this->user->getNews();
$this->load->vars($data);
}
Model
function getNews(){
$q = $this->db->get('News');
if($q->num_rows() > 0){
return $q->result();
}
return FALSE;
}
View
<?php foreach($news as $row) : ?>
<li><?php echo $row->Title; ?> </li>
<li><?php echo $row->Date; ?></li>
<?php endforeach; ?>
This is the error EDIT ves to news
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: news
Filename: admin/Pocetna.php
Line Number: 64
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: admin/Pocetna.php
Line Number: 64
Using WAMP, NetBeans with CodeIgniter. I saw it has to be something with passing data from controller to view but I can't figure it out and been trying few days already, but always having problems.
You're not passing $data to your view. Your controller should be like this:
public function show_news()
{
$this->load->model('user');
$data = [];
$data['news'] = $this->user->get_news();
$this->load->view('news', $data);
}
Your view should also be checking if $news is FALSE, because you'll have some issues with foreach if you loop over the value FALSE. Your model should also be returning result_array not result, foreach cam't loop over objects..
public function get_news()
{
$q = $this->db->get('News');
return($q->num_rows() > 0) ? $q->result_array() : FALSE;
}
Your view should look something like this:
<?php
if($news !== FALSE)
{
foreach($news as $row)
{
echo "<li>{$row['title']}</li>";
echo "<li>{$row['date']}</li>";
}
}
else
{
echo "No news to see here!";
}
?>
Your title also doesn't link up with the error in the post, so that's the solution to the one in the title.

Cannot get message row to delete from database

I'm trying to delete message rows from my database as part of a social networking site for a college project but am getting an error: Severity: Notice Message: Undefined index: id in my view. Any help much appreciated!!!!
This is my method in the Model:
function delMessage($id)
{
$this->db->where(array('id' => $id));
$this->db->delete('messages');
}
This is my method in my Controller:
function delMessage($id) {
$this->messages->delMessage($id);
redirect('message');
}
And this is the code in my view:
if(!empty($messages)){
foreach($messages as $message):
$delete = $message['id'];
var_dump($message); ?>
<li><?=$message['from']?> says...: "<?=$message['message']?>"(<?=anchor("message/delMessage/$delete", 'delete')?>)</li>
<?php endforeach?>
<?php }else{ ?>
<?php echo 'No Messages to View'; }?>
The way you have this written you are calling the view without passing any data to it. If you're going to loop through an array in your view, you have to pass the array from your controller.
Your controller needs to look more like the following:
function delMessage($username) {
$this->load->model('messages_model');
$data['messages'] = $this->messages->deleteUserMessage($username);
$this->load->view('message', $data);
}
In order for that to work, your model has to do more than just delete. It also has to query the database and return the array $messages.
I could try to help you more, but looking at your code I can't figure out what you're trying to do. You've assigned the variable $delete, but you never used it. You are dumping the array on each loop, and you're echoing 'from' each time. At this point, that's like Egyption heiroglyphics. Provide some more info please.
UPDATE BASED ON THE NEW INFORMATION PROVIDED:
function deleteUserMessage($username) {
$this->db->where('from', $username);
$this->db->or_where('to', $username);
$query = $this->db->get('messages');
if ($query->num_rows() > 0){
$messages = $query->result_array();
$this->db->where('from', $username);
$this->db->or_where('to', $username);
$this->db->delete('messages');
return $messages;
}
}

Categories