我有一些PHP代码,我需要从MySQL数据库返回偶数个结果.我正在使用mysqli扩展来执行我的查询.
我的代码目前大约是这样的:
//assume we already have a database connection $query = "SELECT id FROM movies WHERE publish = 1 AND showimage = 1 ORDER BY date DESC LIMIT 6"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { //do some stuff }
如您所见,我将查询限制为6行,但在某些情况下,将返回更少的行.如果只返回3行,我想扔掉最后一行,只保留2行.
我如何在MySQL查询或mysli中执行此操作?
提前致谢.
我可能会用PHP而不是SQL来做这件事.在while
-loop中,保留一个计数器,当你离开循环时,检查计数器.如果它很奇怪,扔掉最后一次迭代的结果.
我想象这样的事情:
// row counter $counter = 1; // loop through each row while($row = $result->fetch_assoc()) { // If there is more than one row remaining // OR if the current row can be divided by two if (($result->num_rows - $counter) > 1 || ($counter % 2)) { // result code for even rows $counter++; } else { // break out of the loop break; } }