使用此代码:
<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$img1 = '';
foreach ($rows as $row) {
$Rpdimg1 = $row['pdimg1'];
$img1 .= $Rpdimg1;
}
UPDATED TO INCLUDE BELOW:
$stmt = $pdo->prepare("SELECT * FROM products WHERE pdcat LIKE 'collectibles%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$img2 = '';
foreach ($rows as $row) {
$Rpdimg2 = htmlspecialchars($row['pdimg1']);
$img2 .= $Rpdimg2;
}
$cats = array(
array(
"title" => "FASHION",
"img" => $img1
),
array(
"title" => "COLLECTIBLES & ART",
"img" => $img2,
)
);
foreach ($cats as $cat): ?>
<?php echo $cat["title"]; ?>
<img src="images/<?php echo $cat["img"]; ?>">
<?php endforeach; ?>
我在Firefox的Inspector工具中显示了以下结果:
<img src="images/shirt.jpgpants.jpg">
[But on the webpage, this displays as a broken image.]
但是我想要是这个结果:
<img src="images/shirt.jpg">
<img src="images/pants.jpg">
[However, I would like the above results displayed as IMAGES, not as html text.]
那两个图像是从我的数据库中回显的值。它们来自我的products
表:
pdid | pdimg1
-----------------
1 | shirt.jpg
2 | pants.jpg
所以基本上
1)我正在从数据库表products
中选择行
2)我将它们作为变量插入到数组中(用于其他目的)
3)我正在使用一个foreach循环从该数组中回显那些变量
4)现在的问题在于,这些IMAGE变量以单字(shirt.jpgpants.jpg
)的形式聚集在一起,而不是作为单独的值,并且没有被包装在其OWN img
标记中,而是在同一img
标签下捆在一起。
5)因此,我在上面以粗体演示了所需的结果。我将如何实现?谢谢
答案 0 :(得分:2)
使用额外的多维数组变量。像这样
<?php
$int_data = array();
foreach ($rows as $row) {
$int_data[] = array(
"title" => $row['title'];
"image" => $row['pdimg1'];
);
}
?>
现在使用title
显示image
和foreach loop
<?php
foreach ($int_data as $data) { ?>
Title : <?php echo $data['title]; ?> <br/>
Image : <img src="path/<?php echo $data['image]; ?>"> <br/>
<?php
} ?>
答案 1 :(得分:0)
您需要在循环内进行数组分配,并减少代码,如下所示:
<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$cats = array();
foreach ($rows as $row) {
$cats[] = array(
"title" => $row['title'];
"img" => $row['pdimg1'];
); // you can add as many column as you get from query
}
foreach ($cats as $cat): ?>
<?php echo $cat["title"]; ?>
<img src="images/<?php echo $cat["img"]; ?>">
<?php endforeach; ?>
答案 2 :(得分:0)
<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) { ?>
<img src="images/<?= $row['pdimg1']; ?>">
<?php } ?>