Passing result() from Model to View in CodeIgniter
The error Call to a member function result() on a non-object occurs because you are trying to access a database query object that was never assigned to a variable. In your controller, the line $this->db->get_where(...)->result() executes the query immediately and returns an array of results (or an empty array). You then discard this data by not assigning it to any variable. When your view tries to call foreach($query->result() as $row), the variable $query is undefined or null, causing the fatal error.
To fix this, you must separate the execution of the query from the retrieval of the result set, and then pass that data explicitly to your view. CodeIgniter's Active Record class allows you to chain methods, but the method responsible for fetching the dataâlike result() or row()âreturns a new object or array that needs to be captured.
Correcting the Controller Logic
In your controller, modify the function to store the result of the query in a variable before passing it to the view. Here is the corrected implementation:
function files()
{
$owner = $this->auth->get_user();
// Execute the query and capture the result set
$data = $this->db->get_where('files', array('owner' => $owner))->result();
$this->load->view('account/files', compact('data'));
}
Notice two critical changes:
- Capturing the Result: The result is assigned to
$data. This ensures you have a reference to the array of objects returned byresult(). - Using
compact(): When loading the view, usecompact('data')to pass the variable explicitly. While passing$datadirectly works if it's in the local scope, usingload->viewwithout arguments might not populate the$queryor$datavariable depending on your specific CI version and configuration. Explicitly passing the data is safer.
Updating the View
Your view should now iterate over the array provided by the controller. Since $this->db->get_where(...)->result() returns an array of objects (in most standard CI configurations), you can iterate directly over that array. You do not need to call result() again in the view; that was already done in the controller.
<?php foreach($data as $row): ?>
<span><?php echo $row->name; ?></span>
<?php endforeach; ?>
If you are using CodeIgniter 3, the result() method returns an array of objects representing the rows. If you use get_where with a single row expected, you might get a single object instead of an array, but since you are listing files, an array is expected. Always check if $data is empty before looping to avoid rendering incomplete UIs when no records match the owner's ID.
Security Considerations
Your original code snippet contained a significant security vulnerability in the SQL construction. You wrote:
array('owner =' => '$owner')
Embedding variables directly into SQL strings like this allows for SQL Injection attacks. Even though CodeIgniter's Active Record class sanitizes some inputs, it is best practice to use placeholders when possible or ensure the input comes from a trusted source.
In your case, $this->auth->get_user() likely returns a user ID. If that method returns a string, you should sanitize it before using it in the query. A safer approach often involves binding parameters if your CI version supports it, or at least ensuring the variable is an integer:
$owner_id = (int) $this->auth->get_user(); // Ensure it's treated as an ID
$this->db->get_where('files', array('owner' => $owner_id))->result();
Alternative Approaches in Modern CodeIgniter
If you are working with a newer version of CodeIgniter (such as 4.x), the Active Record interface changes significantly. In CI 4, you would typically use the Query Builder or Eloquent ORM, and the syntax for fetching results differs. However, the core principle remains identical: execute the query in one step and pass the resulting data object or array to the view.
If you are maintaining a legacy CodeIgniter project and want more robust database handling, consider refactoring your models to handle the get_where logic internally. This keeps your controllers clean and ensures that the view always receives a consistent data structure, whether it's an array of rows or a single object.
For further resources on database interactions in PHP frameworks, you might find additional insights at https://laravelcompany.com regarding modern practices in application architecture.