记录查询结果以用于进一步查询

时间:2018-01-16 08:06:05

标签: php mysql select

我无法正确解释但我在页面(新闻网站主页)上有几个不同的循环查询来选择文章并希望"记录"每篇文章的ID,以便从其他查询结果中排除此类ID。

Select rand from database ... result = ID's 3, 99, 6
$selected = 3, 99, 6
Select rand from database WHERE ID != $selected ... result = ID 51
$selected = 3, 99, 6, 51
Select rand from database WHERE ID != $selected ... result = ID 4

我无法解决如何记录"已选择的ID已逐渐增加,然后再使用它以防止同一文章出现两次。

1 个答案:

答案 0 :(得分:0)

创建一个数组,在其中添加所有结果ID,然后将该数组爆炸为下一个sql。像这样的东西:

$selectedIds = array();
// make first query, get results in loop. im not writing the query execution here, just the loop after
while($row = mysqli_fetch_assoc($res)){
    $selectedIds[] = $row['id']; 
    // do your other stuff here (single article generation)
}

// for further queries you can make the WHERE clause like this
$query = "SELECT rand FROM table WHERE ID not in (".explode(', ', $selectedIds).")";

// this will make the actual query look like this:
// SELECT rand FROM table WHERE ID not in (3, 99, 6)