I tried different ways, but so far nothing. There are similar topics here but they don’t seem to address my particular situation. I’d like to display a single user profile image from an “images” table with a foreign key link to a “users” table. I have a scenario that works but it’s displaying multiple images with a “foreach” statement. The images are also saved in the local “uploads” folder in the root directory. Here is the code that works for multiple images in the view:
<?php foreach($images_model as $images):?>
<img src="<?php echo base_url()."uploads/".$images->fileName;?>" alt="" class="img-thumbnail">
Where “fileName” is the column from the “images” table. The images_model looks like this:
function get_images(){
$this->db->from('images');
$this->db->order_by('date_uploaded', 'asc');
$query = $this->db->get();
return $query->result();
}
The image-upload section from the controller is below:
if($this->upload->do_upload()) {
$file_data = $this->upload->data();
$data['user_id'] = $this->session->userdata('user_id');
$data['fileName'] = $file_data['file_name'];
$data['filePath'] = $file_data['full_path'];
$data['fileType'] = $file_data['file_type'];
$data['fileSize'] = $file_data['file_size'];
$data['date_uploaded'] = date('Y/m/d H:i:s');
}
Here is the necessary portion of the ‘images’ table:
Is there a painless way to display a single image from the “images” table that would take into account the active “user_id” which is the foreign key in the “images” table? In other words, to display a user’s desired image as profile.
Thank you for helping. Appreciate any and all input.
In your model function get_images
you are getting all the records from the table so multiple images are displaying.
You have user_id
in your session use it to get one user record.
Controller
public function SingleUserImage(){
$data['images'] = $this->images_model->get_images();
return $this->load->view('filename', $data);
}
Change model query like this
MODEL
function get_images(){
return $this->db->get_where('images', ['user_id' => $this->session->userdata('user_id')])->row();
}
You have single user record(only one row) so no need to use foreach
loop
View
According to table data that you have provided, image full path is saved use only variable in the src
attribute of img
tag
<img src="<?php echo $images->fileName;?>" alt="" class="img-thumbnail">
Update:-
According to your requirement with the loop use this
<?php foreach($images_model as $images):
if($images->user_id == $this->session->userdata('user_id')):?>
<img src="<?php echo base_url()."uploads/".$images->fileName;?>" alt="" class="img-thumbnail">
<?php endif; endforeach;?>