Joe Scotto Joe Scotto - 3 months ago 8
PHP Question

How would I add the data from this query to an array?

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>";
}

Answer

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