Reputation: 10877
Is there a way that I can put the data from the while loop into an array and output it using echo? I've tried defining an array and just appending it with .=
but it does not add.
$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>";
}
Upvotes: 0
Views: 27
Reputation: 9782
You can get all the data in an array with:
$data = $prep->fetchAll(PDO::FETCH_ASSOC);
To display it, you can close PHP with ?>, then use the alternate syntax for nice clean 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 ?>
Upvotes: 0
Reputation: 4747
Try to add output in an array and then use 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
Upvotes: 1