我有一个包含一些行的 mysql 表。
Select 得到一个 (LIMIT 1) 行。在一个计数器之后,它会重新加载并随机获得另一行。但有时他也会得到同样的结果(随机原因)。
我如何设置他不获取最后一行? 问题是,我不能在 mysql 中这样做。我必须在 session 中或仅在该站点上执行此操作。
我试过了:
$_SESSION['ads'] .= ','.$adid;
将广告放在“广告”SESSION 中并在此处选择之前阅读它
session_start();
$ads = substr($_SESSION['ads'], 1);
$ads = str_replace(",", "','", $_SESSION['ads']);
在SELECT中就是那个
AND id NOT IN ('".$ads."')
但有时,我不知道为什么,他保存了两个项目或其他东西......我不明白为什么,因为 SELECT 是 LIMIT 1
任何想法如何做到这一点或是否有 mysql 函数?
出于任何原因,脚本加载了 SELECT 或其他东西的两倍 这是代码:
$query = "SELECT * FROM ads ORDER BY RAND() LIMIT 1;";
while($row = $result->fetch_assoc()) {
$adid = $row["id"];
$_SESSION['ads'][] = $adid;
}
echo 'adid: '. $adid;
print_r($_SESSION['ads']);
他在那里打印:
Array
(
[0] => 6
[1] => 3
)
我不知道,为什么他把 2 放在那里。因为 $adid 的回显只显示一个!
最佳答案
也许可以尝试这样的事情:
1/创建一个新 session 并创建一个空数组:
session_start();
if (empty($_SESSION['ads']))
$_SESSION['ads'] = array();
2/你是否在这个数组中选择并添加id:
if (empty($_SESSION['ads']) {
// 1. Do your select with no where condition
// 2. Fetch the result
$data = /* result of the select */;
// 3. Add the selected id in your session array
$_SESSION['ads'][] = $data['id'];
} else {
// 1. Do your select but with a WHERE condition
$query = "SELECT...
WHERE id NOT IN ( " . implode( "', '" , $_SESSION['ads'] ) . " )";
// 2. Fetch the result
$data = /* result of the select */;
// 3. Add the selected id in your session array
$_SESSION['ads'][] = $data['id'];
}
这是你要找的吗?
关于PHP MySQL 没有得到最后选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51285461/