MySQL仅返回符合条件的结果

时间:2019-09-06 15:26:59

标签: php mysql

我正在尝试仅选择数据库中符合确切条件的项目,在这种情况下,我需要使该项目处于活动状态并处于激活状态。然后填充轮播,并且箭头按ID导航到该项目。

/* mySql  code */
if ($select = $db -> prepare("SELECT id, name, type, active, abv, ibu, og, hops, color, description, growlers, tap, cans, bottles, image FROM beers WHERE tap = 'Yes' AND (active = 'Yes') AND (id = ?)"))
{
    $select -> bind_param('s', $_GET['id']);
    $select -> execute();
    $select -> bind_result($id, $name, $type, $active, $abv, $ibu, $og, $hops, $color, $description, $growlers, $tap, $cans, $bottles, $image);
    $select -> fetch();
    $select -> close();
}

/* carousel  code */
<a id="prev" class="controls" href="./?page=tapbeer&id=<?php echo $_GET['id'] - 1; ?>">
 <i class="fal fa-angle-left"></i>
</a>
<a id="next" class="controls" href="./?page=tapbeer&id=<?php echo $_GET['id'] + 1; ?>">
  <i class="fal fa-angle-right"></i>
</a>

我只希望下一个符合条件的ID,而不是序列中的下一个ID。

例如,我们有5个项目,其中三个处于活动状态,两个处于点击状态

+-------+-------+--------+------+
| id    | name  | active | tap  |
+-------+-------+--------+------+
| 1     | beer1 | Y      | Y    |
+-------+-------+--------+------+
| 2     | beer2 | Y      | N    |
+-------+-------+--------+------+
| 3     | beer3 | N      | N    |
+-------+-------+--------+------+
| 4     | beer4 | Y      | Y    |
+-------+-------+--------+------+
| 5     | beer5 | M      | N    |
+-------+-------+--------+------+

我只希望在旋转木马中显示Beer1和Beer4。

我一直遇到的问题是所有ID都会滚动浏览,并在轮播中显示为空,因为它们与条件不匹配,因为我们查看ID并加或减1以获得顺序的下一个ID。

1 个答案:

答案 0 :(得分:1)

获取下一个和上一个值的查询是:

SELECT id
FROM beers 
WHERE tap = 'Yes' AND active = 'Yes' AND id > ?
ORDER BY id ASC
LIMIT 1

SELECT id
FROM beers 
WHERE tap = 'Yes' AND active = 'Yes' AND id < ?
ORDER BY id DESC
LIMIT 1

?应该替换为当前ID。

执行这些查询,并获得下一个/上一个链接所需的id

基本上是:

if ($select = $db -> prepare("SELECT id, name, type, active, abv, ibu, og, hops, color, description, growlers, tap, cans, bottles, image FROM beers WHERE tap = 'Yes' AND (active = 'Yes') AND (id = ?)"))
{
    $select -> bind_param('s', $_GET['id']);
    $select -> execute();
    $select -> bind_result($id, $name, $type, $active, $abv, $ibu, $og, $hops, $color, $description, $growlers, $tap, $cans, $bottles, $image);
    $select -> fetch();
    $select -> close();


    $nextId = $db->prepare('query_1');
    $nextId -> bind_param('s', $_GET['id']);
    $nextId -> execute();
    $nextId -> bind_result($next_id);
    $nextId -> fetch();
    $nextId -> close();

    $prevId = $db->prepare('query_2');
    $prevId -> bind_param('s', $_GET['id']);
    $prevId -> execute();
    $prevId -> bind_result($prev_id);
    $prevId -> fetch();
    $prevId -> close();
}

/* carousel  code */
<a id="prev" class="controls" href="./?page=tapbeer&id=<?php echo $prev_id; ?>">
 <i class="fal fa-angle-left"></i>
</a>
<a id="next" class="controls" href="./?page=tapbeer&id=<?php echo $next_id; ?>">
  <i class="fal fa-angle-right"></i>
</a>