php - 将 MySQL 查询限制为偶数个结果

标签 php sql mysql mysqli limit

我有一些 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 查询或 MySQLi 中执行此操作?

最佳答案

我会想象这样的事情:

// 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;
    }
}

关于php - 将 MySQL 查询限制为偶数个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/453245/

相关文章:

PHP Sum Array - 对数组的所有元素求和

where-clause - Sql在WHERE子句中选择空值和非空值

MySQL 时间戳返回为日期时间,而不是整数

mysql - 如何在没有 DROP 数据库权限的情况下从命令行删除所有 MySQL 表?

sql - 列中什么时候为空值 "safe"?

php - 如何在该特定页面上选择导航菜单?

php - 使用 mod_rewrite 将参数附加到查询字符串

javascript - 想要在多个网页中添加同一段文字

php - 点击 "Add"按钮后如何更改答案按钮?

sql - 如何在SQL Server 2008中获取时间字段的总和