이 오류가 발생하는 이유를 이해할 수 없습니다. 내가 볼 수 있듯이 내가 올바르게 사용하는 함수는 데이터베이스에있는 데이터 배열을 반환합니다. 배열의 각 데이터를 에코하려면 foreach()
을 사용하지만 오류 : Warning: Invalid argument supplied for foreach()
이 표시됩니다.배열을 사용할 때 foreach 오류에 대한 잘못된 인수 가져 오기
// 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;
}
그리고 간체 foreach 루프 :
<?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
}
?>
는 그래서이 오류를 일으키는 여기
함수인가?감사합니다.
SQL 쿼리에서 게시물을 검색하지 않으면 $ result가 정의되지 않았기 때문에 함수에서 null이 반환됩니다. retrieve_posts()에있는 while 루프 앞에 빈 배열로 정의하십시오. –
@MarkBaker : exactly – ducin
모든 행을 얻기 위해'return $ stmt-> fetchAll()'을하는 것은 어떻습니까? post와 name이 실제로 jacks_barbers_reviews의 컬럼 인 한'foreach'에 대해서는 아무런 문제가 없습니다. '*'를 사용하지 마십시오. – Sylwester