【发布时间】:2016-03-08 11:29:05
【问题描述】:
我需要检查下一个和上一个 MYSQL 行/循环(相对于当前的 while 循环)的图像大小条件是否为真,并据此用 PHP 安排当前循环的布局。
为了测试和验证代码是否正常工作,我正在检索每行的图像大小,并且只想输出每个循环的布局条件以及帖子 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
?>
输出:
Current: square (ID: 8674)
Previous: square (ID: 76)
Current: horizontal (ID: 8667)
Next: square (ID: 8674)
Previous: square (ID: 76)
Current: horizontal (ID: 8664)
Next: horizontal (ID: 8667)
Previous: square (ID: 76)
Current: horizontal (ID: 8633)
Next: horizontal (ID: 8664)
Previous: square (ID: 76)
Current: square (ID: 8632)
Next: horizontal (ID: 8633)
Previous: square (ID: 76)
【问题讨论】:
标签: php mysql loops mysqli while-loop