So I am creating carousel for my web application I am using new CodeIgniter 4. So far I have successfully managed to upload images however I can't seem to fetch images to display it on front end. It gives me following error - Attempt to read property "bannerimg" on bool.
Edit - I am trying to fetch all images from database (currently there are 4 images stored)
My database table
Database table for carousel - Please check this image too!
Here is the code below
Function to get images in AdminModel
//This functions gets the images from db
public function getBanner() {
$builder = $this->db->table('tblbanner');
$result = $builder->get();
if(count($result->getResultArray()) == 1) {
return $result->getRow();
} else {
return false;
}
}
Admin Controller
public function banners()
{
if(!session()->has('logged_staff')) {
return redirect()->to(base_url(). "/team");
}
$data = [];
$data['validation'] = null;
$suid = session()->get('logged_staff');
$data['getad'] = $this->adminModel->getBanner(); // This line of fetches the images from database.
$data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/banners", $data);
echo view("team/Templates/footer_panel");
}
View File
<div >
<div >
<table id="jsdata">
<thead>
<tr>
<th >Edit Image</th>
<th >Ad Image</th>
<th >Upload Date</th>
<th >Delete Image</th>
</tr>
</thead>
<tbody>
<tr>
<td ><a ><i ></i></a></td>
<td >
**// The image fetched from database is displayed here //**
<?php if($getad->bannerimg != '') : ?>
<img src="<?= $getad->bannerimg; ?>" alt="Ad">
<?php else : ?>
<img src="<?= base_url(); ?>/public/assets/img/no-image.png" alt="Ad">
<?php endif; ?>
**// The image fetched from database is displayed here //**
</td>
<td ><?= $getad->uploaded; ?></td>
<td ><a ><i ></i></a></td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- /.card-body -->
</div>
CodePudding user response:
If you have more than one image in that table then this will return false
:
if(count($result->getResultArray()) == 1) {
return $result->getRow();
} else {
return false;
}
So $data['getad']
and in the view $getad
will be false
. In addition, you fetch an array but then try and access it as an object $getad->bannerimg
.
Since you only want one row, get rid of the if
statement and just return
an object:
return $result->getRow();
Then in your template, just:
<?php if(!empty($getad->bannerimg)) : ?>