0

I'm facing an issue where I execute a SQL query, and then need to run a foreach twice loop against the result.

The first loop runs, and echos out perfectly fine, however, when running the loop again, it returns no results.

$sql = "SELECT * FROM customers";
$stmt = $conn->prepare($sql);
$stmt->execute();

foreach($stmt as $row) {
    echo $row['Name'] . "<br>";
}

foreach($stmt as $row) {
    echo $row['Name'] . "<br>";
}

Of course, I've written this example as a simplification of what I'm actually using it for.

Running something like this below does work, but I'd like to know if there's a more elegant way of solving my issue.

$sql = "SELECT * FROM customers";
$stmt = $conn->prepare($sql);
$stmt->execute();

$stmt2 = array();

foreach($stmt as $row) {
    echo $row['Name'] . "<br>";
    array_push($stmt2, $row);
}

foreach($stmt2 as $row) {
    echo $row['Name'] . "<br>";
}
roweneil
  • 105
  • 8
  • Why the downvote? OP states the problem correctly, adding what they've tried. When you're unknown to pointer, this is very odd behaviour. – Martijn Jul 25 '17 at 15:17
  • My answer didn't fix it, try the above previous comments link – Martijn Jul 25 '17 at 15:22

0 Answers0