有没有办法可以将while循环中的数据放入数组并使用echo输出?我尝试过定义一个数组,然后用.=
添加它,但它没有添加。
$query = "SELECT * FROM coils WHERE name like '%$term%' or
resistance like '%$term%' or
wraps like '%$term%' or
wire_one like '%$term%' or
wire_two like '%$term%' or
wire_three like '%$term%' or
wire_four like '%$term%' or
wire_five like '%$term%' or
wire_six like '%$term%'
LIMIT 25";
$prep = $db->getConnection()->prepare($query);
$result = $prep->execute();
$rowCount = $prep->rowCount();
if ($rowCount <= 0) {
echo "<script>alert('No Results, please try another search');</script>";
}
while($row = $prep->fetch(PDO::FETCH_ASSOC)) {
echo "<a href='coil.php?id=" . $row['uniqueid'] . "'>";
echo "<div id='search_result'>";
echo "<div id='search_title'>Name: " . $row['name'] . "</div>";
echo "<div id='search_ohms'>Resistance: " . $row['resistance'] . "</div>";
echo "<div id='search_wraps'>Wraps: " . $row['wraps'] . "</div>";
echo "<div id='search_around'>Wrapped Around: " . $row['wrapped'] . "</div>";
echo "<div id='search_description'>" . $row['description'] . "</div>";
echo "</div>";
echo "</a>";
}
答案 0 :(得分:1)
尝试在数组中添加输出,然后使用implode()
。
$temp = array();
while($row = $prep->fetch(PDO::FETCH_ASSOC)) {
$temp[] = "<a href='coil.php?id=" . $row['uniqueid'] . "'>";
$temp[] = "<div id='search_result'>";
$temp[] = "<div id='search_title'>Name: " . $row['name'] . "</div>";
$temp[] = "<div id='search_ohms'>Resistance: " . $row['resistance'] . "</div>";
$temp[] = "<div id='search_wraps'>Wraps: " . $row['wraps'] . "</div>";
$temp[] = "<div id='search_around'>Wrapped Around: " . $row['wrapped'] . "</div>";
$temp[] = "<div id='search_description'>" . $row['description'] . "</div>";
$temp[] = "</div>";
$temp[] = "</a>";
}
echo implode(' ', $temp); //with or without space
答案 1 :(得分:0)
您可以使用以下命令获取数组中的所有数据:
$data = $prep->fetchAll(PDO::FETCH_ASSOC);
要显示它,您可以使用?&gt; 关闭PHP,然后使用替代语法来获得干净的HTML:
<?php foreach ($data as $row) : ?>
<a href="coil.php?id=<?= htmlentities($row['uniqueid']) ?>">
<div id='search_result'>
<div id='search_title'>Name: <?= htmlentities($row['name']) ?></div>
<div id='search_ohms'>Resistance: <?= htmlentities($row['resistance']) ?></div>
<div id='search_wraps'>Wraps: <?= htmlentities($row['wraps']) ?></div>
<div id='search_around'>Wrapped Around: <?=htmlentities($row['wrapped']) ?></div>
<div id='search_description'><?= htmlentities($row['description']) ?></div>
</div>
</a>
<?php endforeach ?>