CodeIgniter get_where - php

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.

Related

render data via PDO::FETCH_FUNC vs loop

I've been using 2 methods to render data.
The first one:
function name($id,$name){
return '<div id="'.$id.'">'.$name.'</div>';
}
echo implode($pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_FUNC,'name'));
The second one:
$users = $pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_OBJ);
foreach($users as $user){
echo name($user->id,$user->name);
}
I don't really understand how PDO::FETCH_FUNC works. I already tried to figure it out. However, this is not so well-documented.
Could anybody please explain this fetch mode? And also, which one performs better? Thank you.
Both methods are wrong and you have to learn how to use templates and how to separate business logic from presentation logic.
$users = $pdo->query("SELECT id,name FROM user")->fetchAll(PDO::FETCH_OBJ);
tpl::assign('users', $users);
is ALL the code for the business logic part.
then in template
<?php foreach $users as $row): ?>
<div id="<?=$row->id?>"><?=$row->name?></div>
<?php endforeach ?>
Frankly, your business logic should contain not a trace of HTML while presentation logic should contain not a single database call.
Here is an example:
$stmt = $pdo->query('SELECT id, name FROM user');
$data = $stmt->fetchAll(PDO::FETCH_FUNC, array('Foo', 'name'));
Class Foo {
public static function name($id, $name) {
return '<div id="'.$id.'">'.$name.'</div>';
}
}
So basically FETCH_FUNC mode fetches records to user defined function. This is useful because you can manipulate the result.
Use static method if you are not passing in an object of the class. You can just pass in an object and not use static method just the way #Barmar noted in comments.

How do i call the function I created in my Model on the view

I just created this function in the model to see who im following in my social network... how do i call it in the view??
function isfollowing($following){
$user_id = $this->session->userdata('uid');
$this->db->select('*');
$this->db->from('membership');
$this->db->join('following', "membership.id = following.tofollow_id");
$this->db->where("tofollow_id","$following");
$this->db->where("user_id", "$user_id");
$q = $this->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
Now in my VIEW how do i call it being that i had already made a function to get the current logged on user's id and that is equal to $r->id
How do i call it here?? what goes after the "==" in that if statement?
THE VIEW
<?php if ( $r->id == ): ?>
It is not a good practice to call model function from view.
There are some alternatives about it. You can use anyone you like.
First
When you are loading a view call your model function and pass it in a variable
than this variable will be passed to view.
Controller
$following_status = $this->my_model->isfollowing($following);
$data['following_status'] = $following_status;
$this->load->view('my_view',$data);
View
<p>$following_status</p>
Secound
If you want to be independent of model you can create helper which you can
use anywhere in the application. You will have to create a CI instance to
get it working.
custom_helper.php
function isfollowing($following)
{
$CI = get_instance();
$user_id = $CI->session->userdata('uid');
$CI->db->select('*');
$CI->db->from('membership');
$CI->db->join('following', "membership.id = following.tofollow_id");
$CI->db->where("tofollow_id","$following");
$CI->db->where("user_id", "$user_id");
$q = $CI->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
View
//load the custom helper before using it (you can autoload of in autoload.php)
//or use common way $this->load->helper('custom');
<p>isfollowing($yourparameter)</p>
You do the following:
(1) Load your model in the controller that creates your page or auto load it
(2) In your view, type something like:
$this->The_custom_model->isfollowing($theinputvariable)
where The_custom_model is the model where you defined the isfollowing() function.
$theinputvariable is the appropriate argument value for your function. Keep in mind that you have specified an object as the argument to your function so you need to think about that.
this is an amended version to what raheel posted showing an if check - probably not necessary for your question, but to give you some things to think about...
// check to see if anything come back from the database?
if ( ! $data['following_status'] = $this->my_model->isfollowing($following) ) {
// nothing came back, jump to another method to deal with it
$this->noFollowers() ; }
// else we have a result, and its already set to data, so ready to go
else {
// do more here, call your view, etc
}
databases can go down even if the web page is working so its good to get in the habit of checking the results. the more error checks you can do in your controller and models, the cleaner your view files will be.
To access model into your view you first load it into autoload file like this
$autoload['model'] = array('model_name');
then in view you can get it by using this line of code
$this->model_name->isfollowing($following)
in isfollowing you will pass your tofollow_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}

PHP MVC loop in the view

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'];
}

passing sql query results from controller into view with code igniter

So I'm having this problem, it should be pretty simple, but I don't know why I can't figure it out. I"m new to the whole idea of MVC, and I'm trying to pass a database query from my controller into a view and display the results in the view. The way I'm doing it now says "undefined variable, sql" when I load the view. This is what I have:
CONTROLLER
function make_login()
{
//Select list of departments for dropdown
$this->load->database();
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
$this->load->view('siteheader.php');
$this->load->view('makelogin.php', $sql->result_array());
$this->load->view('sitefooter.php');
}
VIEW
<?php
foreach($sql->result_array() as $row)
{
echo $row['departmentName'];
}
?>
(If I just echo it out in the controller, it displays the results)
Any help would be awesome...
THANKS!
few tips ~
your make_login should be in a model. your controller will look something like this:
function make_login
{
$this->load->model('login_model'); // whatever you call it
$data['departments'] = $this->login_model->get_departments();
/* note - you don't need to have the extension when it's a php file */
$this->load->view('siteheader');
$this->load->view('makelogin', $data);
$this->load->view('sitefooter');
}
now in your model, have something like:
function get_departments()
{
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
return $sql->result();
/* you simply return the results as an object
* also note you can use the ActiveRecord class for this...might make it easier
*/
}
and finally, your view:
<?php
foreach($departments as $store)
{
echo $store->name . '<br />'; // your fields/whatever you want to output.
}
?>
The SQL query should be done in the model.
Cheap mnemonic device: the D in model = database.
In the Controller, you assign part of the $data array to the results of the query:
$this->load->model('blog_model');
$data['posts'] = $this->blog_model->getPosts();
// Load the view with the data
$this->load->view('blog', $data);
In the Model, you do the actual query:
public function getPosts()
{
// Method chaining supported in PHP 5
$this->db->select('*')->from('posts');
// Assign the query object to a variable
$query = $this->db->get();
// We don't want to return an empty result, so let's handle that error somehow
if (!$query->num_rows() > 0) {
die("There are no posts in the database.");
}
// Make a new array for the posts
$posts = array();
// For the purposes of this example, we'll only return the title
foreach ($query->result() as $row) {
$posts[$row->id] = $row->title;
}
// Pass the result back to the controller
return $posts;
}
Now, in the view, each element of $data will be its own variable:
<div class="post">
<?php foreach ($posts as $id => $title) : ?>
<h1 class="post-title"><?php echo $title; ?> (ID: <?php echo $id; ?>)</h1>
<p class="post-content">
.......
</p>
<?php endforeach; ?>
</div>
That's it!
It seems that either CI is confusing you or you are also new to PHP. They are just functions so you can't pass variables like that.
When passing an associative array it will take the key and make that into a variable with the value in the array, using native PHP functions. What Ross said is exactly what you are supposed to do.
Model: all database stuff
Controller: uses models to pass variables to views
View: outputs the variables (a view should never have any sql in it)
Also note that result and result_array have the same data but result returns objects and result_array returns associative arrays.
foreach($array as $row)
{
echo $row['departmentName'];
}
?>
You need to pass the $array in.
I am not sure what ->load->view() does and how it treats the incoming parameters.

Categories