Fetching All Images from a Database Using PHP and CodeIgniter's ORM System

Understanding the Issue with Fetching All Images from a Database

===========================================================

In this article, we will explore the issue of fetching all images from a database using PHP and its ORM (Object-Relational Mapping) system. The problem lies in how the data is retrieved and processed between the model and view layers.

Background Information


ORM systems like CodeIgniter’s query builder provide an efficient way to interact with databases by abstracting the underlying SQL syntax. In this example, we are using CodeIgniter’s query builder to fetch images from a database.

The issue arises when trying to fetch all images from the database and display them in the view layer. We will delve into the details of how data is retrieved and processed between the model and view layers.

The Model Layer


In the provided model, we have the following method:

public function fetchimage(){
    $this->db->select('u_id,file_name');
    $this->db->from('image');
    if($this->session->userdata('id')){
        $this->db->where('u_id',$this->session->userdata('id'));
        $query = $this->db->get();
        $result = $query->result_array();
        echo '<pre>';print_r($query);die();
    }
    return !empty($result)?$result:false;
}

Here, we are using CodeIgniter’s query builder to fetch the u_id and file_name columns from the image table. If a user is logged in, we filter the results by the user’s ID.

The View Layer


In the provided view, we have the following code:

$this->load->model('user');
$data['uploadData'] = $this->user->fetchimage();
?>
<div class="row">
    <ul>
        <?php if ($data['uploadData']) {
            foreach ($data['uploadData'] as $rowData) { ?>
                <li class="item">
                    <img src="<?php echo base_url('/assets/uploads/files/' .$rowData['file_name']); ??>" >
                </li>
            <?php } } else { ?>
                <p>Image(s) not found.....</p>
            <?php } ?>
    </ul>
</div>
<br>

Here, we are loading the user model and calling its fetchimage() method to retrieve the images. We then loop through each image and display it using an <img> tag.

The Issue


The problem lies in how the data is being retrieved from the database in both layers. Let’s break down what’s happening:

  1. In the model layer, we are calling $query->result_array() to retrieve all rows of the query result as an array. This function returns a single row with multiple columns.
  2. In the view layer, we are using foreach ($data['uploadData'] as $rowData) to loop through each image. However, since $result is being stored in the model and returned in its original format, this results in a single column of data ($rowData) instead of an array of rows.

The Solution


To fix this issue, we need to modify how we are retrieving the data from the database and processing it in both layers. Here’s what we can do:

Modified Model Layer

public function fetchimage(){
    $this->db->select('u_id,file_name');
    $this->db->from('image');
    if($this->session->userdata('id')){
        $this->db->where('u_id',$this->session->userdata('id'));
        $query = $this->db->get();
        $result = $query->row_array();
        echo '<pre>';print_r($query);die();
    }
    return !empty($result)?$result:false;
}

Modified View Layer

$this->load->model('user');
$data['uploadData'] = $this->user->fetchimage();
?>
<div class="row">
    <ul>
        <?php if ($data['uploadData']) {
            foreach ($data['uploadData'] as $rowData) { ?>
                <li class="item">
                    <img src="<?php echo base_url('/assets/uploads/files/' .$rowData['file_name']); ??>" >
                </li>
            <?php } } else { ?>
                <p>Image(s) not found.....</p>
            <?php } ?>
    </ul>
</div>
<br>

Modified Model Layer (Alternative Solution)

public function fetchimage(){
    $this->db->select('u_id,file_name');
    $this->db->from('image');
    if($this->session->userdata('id')){
        $this->db->where('u_id',$this->session->userdata('id'));
        $query = $this->db->get();
        $result = $query->result_array(); // Change this line to retrieve multiple rows
        echo '<pre>';print_r($query);die();
    }
    return !empty($result)?$result:false;
}

However, using $result = $query->row_array() still returns a single row. To fix this issue, we need to use foreach loop on the result directly:

public function fetchimage(){
    $this->db->select('u_id,file_name');
    $this->db->from('image');
    if($this->session->userdata('id')){
        $this->db->where('u_id',$this->session->userdata('id'));
        $query = $this->db->get();
        foreach ($query->result() as $row) { ?>
            <li class="item">
                <img src="<?php echo base_url('/assets/uploads/files/' .$row->file_name); ??>" >
            </li>
        <?php } ?>
    }
}

By making these changes, we ensure that the data is retrieved correctly from the database and processed in both layers.


Last modified on 2025-04-08