简体   繁体   中英

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.

  1. All querying should be performed in the Model.
  2. 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.
  3. 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.
  4. The default comparison of codeigniter's where methods is = , so you don't need to declare the equals sign.
  5. 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:

  1. Load the model (if it isn't already loaded)
  2. Call the model method and pass the owner id as a parameter.
  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM