php - 如果不存在更高的id,如何设置mysql where子句返回到id=1

标签 php mysql

我需要在代码中的某个地方说“如果在当前 id 之后没有找到任何内容,则从 id 1 开始搜索”。我遇到了这样的问题:(例如)我正在查询任何 id > 4 其中状态 == 1 的情况。因为 id 5 没有正确的状态,所以代码没有执行。我需要它返回到 id #1。

mysql表示例

-----------------------------------------
|  id  |  page  |  status  |  referral  |
-----------------------------------------
|  1   |  new   |    1     |  new.php   |
|  2   |  used  |    0     |  used.php  |
|  3   |  lease |    1     |  lease.php |
|  4   |  video |    0     |  video.php |
|  5   |  serv  |    0     |  serv.php
-----------------------------------------

php代码

<?php 
$referral = $_SERVER['HTTP_REFERER'];

$sql = "SELECT * FROM allpages 
        WHERE status = '1' && referral != '$referral' && id > '4'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
       if ($row['status'] == 1){
          echo "<script>
                  setTimeout(function() {
                     window.location.href = '" . $row['url'] . "';
                  }, 10000);        
                </script>";
         break;
       }else { echo "no page to display"; }
    }
}
mysqli_close($conn);
?>

最佳答案

您想要查找第一个大于 4id,否则返回表中的第一个 id。您可以通过按 (id > 4) DESC 排序,然后按 id ASC 排序来完成此操作。这将确保所有 id 的 > 4 将出现在 id 1 之前。同时从 where 子句中删除 id>4 。示例:

SELECT * FROM allpages WHERE status = '1' ORDER BY (id > '4') DESC, id ASC LIMIT 1

关于php - 如果不存在更高的id,如何设置mysql where子句返回到id=1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372501/

相关文章:

php - php中检测ie10、<ie10等浏览器

PHP 表单未发布到 SQL 数据库

mysql - 类型错误 : Cannot set property 'decoder' of undefined

php - 需要帮助构建一个 mysql 查询,将一个变量与两个表进行比较

php - 为每个 jQuery 调用创建新类是最佳实践吗?

php - 在查询中找不到上传的 tmp 文件

php - 如何让我的 PDO 连接更有效率?

javascript - 如何在服务器上设置 "no value"以兼容Backbone?

mysql - (NodeJS、MySQL、AngularJS、Express 4.0)不阻止用户的 api/路由有风险吗?

php - 通过在末尾添加 '@live.com' 来更新电子邮件地址