I have two tables and need to show the first 2 images from images
table that is linked with the id from news
table for each id of the news table.
<?php
$stmt = $con->prepare('SELECT `id`, `title`, `main_image`, `services` FROM `news` ORDER BY `id` DESC');
$stmt->execute();
$stmt->bind_result($id, $title, $main_image, $services);
while ($stmt->fetch()) {
$news[] = ['id' => $id, 'title' => $title, 'main_image' => $main_image, 'services' => $services];
}
$stmt = $con->prepare('SELECT n.id, i.file_name FROM news AS n INNER JOIN images AS i ON n.id = i.new_id LIMIT 2');
$stmt->execute();
$stmt->bind_result($id, $file_name);
while ($stmt->fetch()) {
$images[] = ['id' => $id, 'file_name' => $file_name];
}
foreach ($news as $new) {
$service = explode(", ", $new['services']);
if (in_array('Photo', $service)) {
?>
<div class="col-md-4">
<div class="card">
<div class="ratio ratio-16x9">
<div class="row g-0">
<div class="col-6">
<div class="h-100 me-1 " style="background-image: url(../uploads/<?= $new['main_image'] ?>); background-size: cover;">
</div>
</div>
<div class="col-6">
<div class="vstack gap-1 h-100">
<div class="h-50 " style="background-image: url(../uploads/<?= $images['file_name'] ?>); background-size: cover;"></div>
<div class="h-50 bg-dark-overlay-3 overflow-hidden" style="background-image: url(../uploads/<?= $images['file_name'] ?>); background-size: cover;">
<div class="d-flex justify-content-center align-items-center h-100">
<a class="btn-link text-white mb-0 stretched-link" href="#"> Vidi sve </a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-body px-0 pt-3">
<h5 class="card-title"><a href="post-single-3.html" class="btn-link text-reset fw-bold"><?= $new['title'] ?></a></h5>
<ul class="nav nav-divider align-items-center d-none d-sm-inline-block">
<li class="nav-item">
<div class="nav-link">
<div class="d-flex align-items-center position-relative">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
<?php
}
}
?>
What am I doing wrong?
The reason this is happening is because you are building $images
as an indexed array instead of an associative array. Then when you iterate through the news articles, accessing it via $image['file_name']
does not work because the key file_name
does not exist in the array.
To make it work, you need to change how you create the $images
array. The id of the news article needs to be the key that you append filenames inside.
$images[$id][] = $file_name
Then when you are going through the news articles, you access it by getting the id from the news article:
<?= $images[$new['id']][0] ?>
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.