我需要在代码中的某个地方说“如果在当前 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);
?>
最佳答案
您想要查找第一个大于 4
的 id
,否则返回表中的第一个 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/