PHP MVC loop in the view - php

I consider myself as a php beginner, so it may be possible that this question is too easy for someone, but I got really confused on how to solve it. I am trying to loop something from the database in my views. So, in a quick way I solved it like this:
I've created a function in my model that does the loop and in the same time is creating the html and saves it in a variable. Then, I get that variable from my controller and I pass it in my view. But, it seems that this is not a good way to solve it, since if I want to change my html I need to enter my model function instead some of the view files.
Then, I've created another function in my model that looks like this:
function displayUsers() {
$sql = $this->pdo->prepare('select * from user');
$sql->execute();
while($row = $sql->fetch())
$results[] = $row;
return $results;
}
Now... I take the result in my controller, and send it in the view, but then... I don't know how to extract the results from my variable. I have done something like this:
while($output) {
foreach($output[$i] as $key => $value)
$data[$key] = $value;
echo $data['email'];
$i++;
}
But then, in the end it says to me undefined offset, which means I am referring to an array key that doesn't exist. Can anyone help me on how to solve this issue?

Proper MVC shouldn't have any output in the model or the controller.
Ideally you would have a model that just gets the raw data and returns it in the controller. The controller can then build up an array of values that we'll call data. For example:
Controller
$data['users'] = $this->MyModel->getusers(); // Getting the users from your model
$data['posts'] = $this->MyModel->getposts(); // Getting the posts from your model
$this->getTemplate('userdisplay', $data); // Get the template userdisplay and pass data
This gets the data from the model, and then assigns it to a key within the "data" variable. You can then pass the data variable into the template. You'll then have two variables to work with in the template, $users and $posts.
You'll need a "getTemplate" function that properly maps the data array to individual variables for use in the template, but all of the display should be located in the template.
To answer your specific question at the end, something like this should work in the template:
if (count($users) > 0) {
foreach ($users as $person) {
echo $person['email'];
}
}

You should be able to do this:
foreach($output as $row) {
echo $row['email'];
}

Related

how to get data into view from controller in cakephp

$this->loadModel('Siteconfig');
$data=$this->Siteconfig->find('all');
foreach($data as $data)
{
$email=$data['Siteconfig']['email'];
$companyname=$data['Siteconfig']['companyname'];
$cfa=$data['Siteconfig']['cfa'];
}
Above is Controller
How to get cfa data in view using CAKEPHP?
In your controller method, you can use this
$this->set('var_name_in_view', $cfa); //You will find the variable $cfa as $var_name_in_view in your view(You have to use $var_name_in_view in view)
You can also send multiple variables to your view at once
$this->set(compact('cfa', 'another_variable')); //You can acceess using $cfa and $another_variable
Compact makes an array keeping the variable name as key and variable value as the value for the array key.
Modify your script to
$this->loadModel('Siteconfig');
$data=$this->Siteconfig->find('all');
$cfa = '';
foreach($data as $datum)
{
$email=$datum['Siteconfig']['email'];
$companyname=$datum['Siteconfig']['companyname'];
$cfa=$datum['Siteconfig']['cfa'];
}
$this->set('view_cfa',$cfa);
This will fix it. Your foreach was reassigning $data.

Codeigniter view returned as a string with data

I'm using Codeigniter 3 and im trying to pull in a view to a variable, and pass data to the view for inclusion. But the view is not recognising the data being passed and is telling me the variable doesn't exist.
This is how I'm calling the view:
$view = $this->load->view('notifications/' . $report_type, $data ,true);
And then in the view I'm trying to loop through $data and display as appropriate, like so:
foreach($data as $item){
// echo stuffs
}
I know $data definately contains data as I've var_dump'ed it.
Can I do it like this?
You need to pass an associative array to the loader.
$view = $this->load->view('notifications/' . $report_type, array('data' =>$data) ,true);
Now the variable will be visible at the view.
if model Page_m and method western return a specific value which you need,
$this->data['western'] =$this->Page_m->western();
$this->load->view('notifications/' . $report_type,$this->data);
in your view
foreach($western as $item){
// echo stuffs
}

Pass variable from controller to view

In my controller, I can get the organization name but when I pass it to the view
there's an error. It said invalid argument supplied for foreach( ):
.
This is my codes.
Controller
public function index()
{
$user_id = $this->session->userdata('user_id');
$data['title'] = "User";
$getID['orgID'] = $this->userModel->getOrganizationID($user_id); // used my session user_id to
foreach ($getID['orgID'] as $orgID)
{
$org_id = $orgID->org_id;
$getName['myOrganization'] = $this->userModel->myOrganization($org_id);
foreach($getName['myOrganization'] as $orgName)
{
$name = $orgName->org_name;
$data['name'] = $name;
}
}
$this->load->view('xxxx/xxxx/xxxx',$data);
Model
public function getOrganizationID($user_id)
{
$this->db->select('org_id');
$this->db->from('organization_members');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query->result();
}
public function myOrganization($org_id)
{
$this->db->select('org_name');
$this->db->from('tblorganization');
$this->db->where('org_id', $org_id);
$query = $this->db->get();
return $query->result();
}
My output
First array is my result of $getID['orgID'] = $this->userModel->getOrganizationID($user_id); which I used my user_id session to get all the org_id of the user then
Second array is my result of $getName['myOrganization'] = $this->userModel->myOrganization($org_id); which I used my org_id(from my previous method) to get all the org_name of the user.
Is there going to be more then one result? Because if its only one result then you can use $query->row(); and eliminate the foreach completely.
Always check to make sure your database method worked AND that you actually got a returned value whenever you are making any database call. So i'll let you add the if condition in the database method but in short it should return FALSE if nothing came back. So thats the database method heres one way of doing it in your controller. Note this: $getID['orgID'] is very awkward. You are getting results back from the members table so call it members.
// check for the negative first - if no members came back
if( ! $members = $this->userModel->getOrganizationID($user_id) )
{
// if no results back leave this method
// pass the user id so you can echo it out in the error page
$this->showNoResultsFor($user_id) ;
}
else{
foreach ($members as $member)
{
$org_id = $member->org_id;
// etc etc etc
I'm not a codeigniter expert but looking at your code, I am wondering why you are setting:
$getID['orgID'] = $this->userModel->getOrganizationID($user_id);
First, you are setting an array $getID['orgID'] rather than just using something like $memberships = ...; I'm not sure why you are casting an array.
Secondly, you seem to be referencing a model class without instantiating it:
$this->userModel->getOrganizationID($user_id);
Perhaps codeigniter does some magic? $this refers to this instance and from the code you show, your model is likely in a separate class/file so I am unclear how $this->userModel is referenced in your method, unless you are instantiating it in your Controller's constructor?
From what I see it looks like you are getting the error because you are not supplying a valid object/array to your foreach. Perhaps start by testing you are actually getting a valid return from $this->userModel->getOrganizationID($user_id).

MYSQL and CI Array Of Data

In one of my controllers to fetch all the data for my general view page I use a foreach loop and then $object->column_name but now I have decided I would like to do a couple of things with this data:
Edit it -> It is an edit page for each $object by its $id
Use the $object->name field via the controller to enable me to use it in a $data['pageTitle']= Edit '.$object->name.';
What would be the best way to change the model below so that I can use it for many purposes / different ways of displaying the data for manipulation?
public function showAll()
{
$database = $this->db->get('form');
if($database->num_rows() > 0)
{
$row = $database->result();
}
return $row;
}
It is good practice to keep the database query part in your model rather than the controller.
In your controller you can do something like:
$recs = $this->sample_model->model_function();
foreach ($recs as $r)
{
$r->additional_info_appended_to_each_row = 'whatever';
}
This way you can append an additional variable to each database row for displaying / editing etc.
That code doesn't really show us enough of the relevant code to be able to answer that question. Assuming $database->result() returns an array of rows (a database query's result set) then the data it contains depends on how the query looks. All you show is is $this->db->get('form'), which can mean just about anything.
A generic answer to your question would be: Alter the SQL query to include the id and name fields. Then inject those into your view through your controller. (Or get them directly through the view. That's up to you.)
Not knowing a thing about your controllers or your views, here is an example that assumes your views extend the Smarty template engine.
public function GeneralController
{
public function defaultAction()
{
$model = new GeneralModel();
$objects = $model->getAll();
$view = new GeneralView();
$view->assign("objects", $objects);
$view->show();
}
}
The Smarty template would then use those rows when generating the HTML
{foreach $objects as $object}
<section class="object">
<header>
<h1>{$object->name}</h1>
</header>
<p>{$object->contents}</p>
<footer>
Edit
</footer>
</section>
{/foreach}

CodeIgniter get_where

I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.

Categories