I can not understand why this error is occurring. From what I can see I the function I use correctly returns an array of data that exists on the database. I use a foreach() to echo out each of the data in the array but it gives me the error: Warning: Invalid argument supplied for foreach().
Here is the function:
// Retrieve posts
function retrieve_posts(){
// start new instance of the database connection
global $dbh;
// Get all the posts
$stmt = $dbh->prepare("SELECT * FROM jacks_barbers_reviews ORDER BY date DESC");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
And the (simplified) foreach loop:
<?php
$posts = retrieve_posts();
foreach($posts AS $index){
echo '<div class="test-wrap">'; //contains the individual testimonials
echo '<p>' . $index['post'] . '</p>';
echo '<p style="float:right;font-style:normal;font-size:15px;">By ' .$index['name']. ' ' .$index['date']. '</p>';
echo '<div style="clear:both"></div>';
echo '</div>'; // closes test-wrap
}
?>
So what is causing this error?
Thanks
return $stmt->fetchAll()to get all the rows? I cannot se anything wrong with theforeachas long as post and name really are columns of jacks_barbers_reviews. Consider not using*.