我正在建立一个学院评审系统,我刚刚完成了对数据库的评论。但是,我正在解决如何向用户显示与特定机构相关的所有评论。 以下是我的代码,用于检索评论信息以及离开评论的人的姓名:
$get_review_query = "SELECT * FROM reviews WHERE institute_id = {$id}";
$result = mysqli_query($connection, $get_review_query);
if(!$result) {
die("Database query failed.");
}
$count = mysqli_num_rows($result);
if($count == 0) {
$output = "There're no reviews for this institute.";
} else {
while($row = mysqli_fetch_assoc($result)) {
$review_contents = $row['content'];
$institute_id = $row['institute_id'];
$student_id = $row['student_id'];
$date = $row['created_on'];
$query_student_name = "SELECT f_name, l_name FROM students
WHERE student_id = {$student_id}";
$result1 = mysqli_query($connection, $query_student_name);
if(!$result1) {
die("Database query failed.");
} else {
$row1 = mysqli_fetch_assoc($result1);
$student_f_name = $row1['f_name'];
$student_l_name = $row1['l_name'];
}
}
}
现在我想在页面的某处显示评论:
<!-- display reviews -->
<fieldset>
<legend>Reviews for <?php echo $name; ?></legend>
<br>
<?php
foreach($row as $value) {
?>
<legend><?php echo $student_f_name . " ". $student_l_name; ?> said:</legend>
<div id = "items" class="">
<?php echo $review_contents; ?>
</div>
<br>
<div>
<?php echo $date; ?>
</div>
<?php } ?>
</fieldset>
上述foreach循环不起作用。它可能会创建一个无限循环。我尝试使用带有$ count的for循环作为最大计数器,但这也不起作用。请建议使用for循环打印数据库中的所有评论。
答案 0 :(得分:0)
试试这个
$get_review_query = "SELECT * FROM reviews WHERE institute_id = {$id}";
$result = mysqli_query($connection, $get_review_query);
if(!$result) {
die("Database query failed.");
}
$reviews = array();
$count = mysqli_num_rows($result);
if($count == 0) {
$output = "There're no reviews for this institute.";
} else {
while($row = mysqli_fetch_assoc($result)) {
$query_student_name = "SELECT f_name, l_name FROM students
WHERE student_id = {$student_id}";
$result1 = mysqli_query($connection, $query_student_name);
if(!$result1) {
die("Database query failed.");
} else {
$row1 = mysqli_fetch_assoc($result1);
$row['f_name'] = $row1['f_name'];
$row['l_name'] = $row1['l_name'];
}
$reviews[] = $row;
}
}
if( $reviews ){
?>
<fieldset>
<legend>Reviews for <?php echo $name; ?></legend>
<br>
<?php
foreach($reviews as $review) {
?>
<legend><?php echo $review['f_name'] . " ". $review['l_name']; ?> said:</legend>
<div id = "items" class="">
<?php echo $review['content']; ?>
</div>
<br>
<div>
<?php echo $review['created_on']; ?>
</div>
<?php } ?>
</fieldset>
<?php
}