MYSQL&;PHP while循环在输出前检查上一行和下一行

MYSQL&;PHP while循环在输出前检查上一行和下一行,php,mysql,loops,mysqli,while-loop,Php,Mysql,Loops,Mysqli,While Loop,我需要检查下一个和上一个MYSQL行/循环(相对于当前while循环)的图像大小条件是否为true,并根据该条件,使用PHP安排当前循环的布局 为了测试和验证代码是否正常工作,我正在检索每行的图像大小,只想输出每个循环的布局条件以及post ID 下面的代码对于当前while循环以及下一行项目都可以正常工作,但是对于上一行项目,我得到了相同的常量值 我的错在哪里?有没有更好/更简单的方法?也许是为了避免多次查询 <?php $sql = "SELECT * FROM posts WHERE

我需要检查下一个和上一个MYSQL行/循环(相对于当前while循环)的图像大小条件是否为true,并根据该条件,使用PHP安排当前循环的布局

为了测试和验证代码是否正常工作,我正在检索每行的图像大小,只想输出每个循环的布局条件以及post ID

下面的代码对于当前while循环以及下一行项目都可以正常工作,但是对于上一行项目,我得到了相同的常量值

我的错在哪里?有没有更好/更简单的方法?也许是为了避免多次查询

<?php
$sql = "SELECT * FROM posts WHERE image_featured!='' ORDER BY id DESC LIMIT 5";
$query = mysqli_query($connection, $sql);

while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$current_width = $row["width"];
$current_height = $row["height"];
if ($current_width > $current_height){
$current_layout = 'horizontal';
} // end if
if ($current_width == $current_height){
$current_layout = 'square';
} // end if
if ($current_width < $current_height){
$current_layout = 'vertical';
} // end if

echo 'Current: '.$current_layout.' (ID: '.$id.')<br/>';

$nextsql = "SELECT * FROM posts WHERE id > $id AND image_featured!='' LIMIT 1"; 
$nextquery = mysqli_query($connection, $nextsql);
if(mysqli_num_rows($nextquery) > 0) {
while($nextrow = mysqli_fetch_array($nextquery)){
$next_id  = $nextrow['id'];
$next_width = $nextrow["width"];
$next_height = $nextrow["height"];
if ($next_width > $next_height){
$next_layout = 'horizontal';
} // end if
if ($next_width == $next_height){
$next_layout = 'square';
} // end if
if ($next_width < $next_height){
$next_layout = 'vertical';
} // end if
echo 'Next: '.$next_layout.' (ID: '.$next_id.')<br/>';
} // end while
} // end if

$previoussql= "SELECT * FROM posts WHERE id < $id AND image_featured!='' LIMIT 1"; 
$previousquery = mysqli_query($connection, $previoussql);
if(mysqli_num_rows($previousquery) > 0) {
while($previousrow = mysqli_fetch_array($previousquery)){
$previous_id  = $previousrow['id'];
$previous_width = $previousrow["width"];
$previous_height = $previousrow["height"];
if ($previous_width > $previous_height){
$previous_layout = 'horizontal';
} // end if
if ($previous_width == $previous_height){
$previous_layout = 'square';
} // end if
if ($previous_width < $previous_height){
$previous_layout = 'vertical';
} // end if
echo 'Previous: '.$previous_layout.' (ID: '.$previous_id.')<br/>';
} // end while
} // end if

echo '<hr/>';

} // end while 1
?>

也许您需要添加到查询顺序中,因为从表结果开始,它总是给您相同的解决方案

$previoussql= "SELECT * FROM posts WHERE id < $id AND image_featured!='' ORDER BY id DESC LIMIT 1"; 
$previoussql=“从id<$id和图像特色的帖子中选择*!=”“按id排序描述限制1”;

或者可能是ASC,因为我不知道你的表和结果集,所以你得到了

巴哈哈,天哪,我不敢相信这就是原因!工作起来很有魅力!非常感谢!!:)
$previoussql= "SELECT * FROM posts WHERE id < $id AND image_featured!='' ORDER BY id DESC LIMIT 1";