【问题标题】:How can I combine pagination and filtering in php?如何在php中结合分页和过滤?
【发布时间】:2020-08-12 19:23:05
【问题描述】:

我想显示数据库中的一些产品,并使用分页和复选框进行过滤。我的分页工作正常。当我单击复选框并按“提交”时,我确实会在第一页上得到过滤结果。但是,当我移至第二页或任何其他页面时,复选框会自动变为未选中状态,并且过滤会丢失。 这是我的 HTML 代码:

<form action="" method="get">
  <input type="checkbox" name="brand[]" value="iPhone">iPhone<br>
  <input type="checkbox" name="brand[]" value="iPad">iPad<br>
  <input type="checkbox" name="brand[]" value="Samsung">Samsung<br>
  <input type="checkbox" name="brand[]" value="Huawei">Huawei<br>

  <input type="submit" name="submit" value="Submit">
</form>

<?php include 'display_products.php';?>

我的分页是这样的:

for ($page=1;$page<=$number_of_pages;$page++) {
  if ($page == $page_active) {
    echo '<a class="page-number this-active" href="index.php?page=' . $page . '">' . $page . '</a> ';
  } else {
    echo '<a class="page-number" href="index.php?page=' . $page . '">' . $page . '</a> ';
  }
}

为了应用过滤,我使用了 IF 语句:

if (isset($_GET['brand'])) {
  $filter = implode('","',$_GET['brand']);
  $sql='SELECT * FROM products WHERE brand IN ("' . $filter . '") LIMIT ' . $this_page_first_result . ',' .  $results_per_page;
  $result = mysqli_query($conn, $sql);

  while($row = $result->fetch_assoc()) {
    echo '<div><h3>' . $row['title'] . '</h3><img src="' . $row['image'] . '"<h4>' . $row['price']. '</h4></div>';
  }
} //else display all products from the table of the database

我假设当我转到下一页时,我的复选框未被选中,这个 $_GET['brand'] 变为空并且“else”语句被激活。我试图为这个问题找到解决方案,但其中一些没有效果,有些对我来说太难理解(我是初学者)。您能否简单地解释一下如何保持复选框处于选中状态以及如何在所有页面中保持过滤?我看到了诸如“使用会话”或“将数据保留在 url”之类的想法,但我不知道如何实现它。因此,如果您更具体,我将非常感激。非常感谢!

【问题讨论】:

  • 您能否分享更多代码,包括您的分页..
  • 您应该将用户过滤选项存储在 $_SESSION 中并在每个帖子中更新它们
  • 您的 SQL 查询对 SQL 注入开放,最好修复它。分页的代码在哪里?为什么不将所有复选框的 ID 添加到分页 URL 中?
  • 我已经添加了我的分页代码,谢谢
  • 现在我正在学习如何进行过滤和分页。达到目标后,我肯定会进行 SQL 注入。关于添加到 URL 的 ID,恐怕我不知道它是如何工作的。如果你能多说一点,那就太好了

标签: php database checkbox pagination filtering


【解决方案1】:

如果您要使用 PHP 来生成 brands 复选框(例如,如果有许多品牌可以由管理员随时更改,这将是一个优点),那么也许以下内容可能会给出如何维护的想法checked 每个复选框的状态。

以下是您如何实现既定目标的粗略想法 - 希望对您有所帮助。

<?php
    function getParams(){
        return !empty( $_GET ) ? $_GET : [];
    }
    function buildQuery( $params=array() ){
        $tmp=array();
        foreach( $params as $param => $value ){
            if( is_array( $value ) ){
                foreach( $value as $field => $fieldvalue )$tmp[]=sprintf('%s[]=%s',$param,$fieldvalue);
            } else $tmp[]=sprintf('%s=%s',$param,$value);
        }
        return urldecode( implode( '&', $tmp ) );
    }

?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Filtering & maintaining checkbox "checked" status</title>
        <style>
            fieldset{
                margin:1rem;
                padding:1rem;
                border:1px dotted gray;
            }
            #paging > a{
                padding:0.25rem;
                border:1px solid transparent;
            }
            #paging > a.active{
                border:1px solid red;
                background:yellow;
            }
        </style>
    </head>
    <body>
        <form method='get'>
            <fieldset>
                <?php
                    # an array of brands.. this could likely be from the database
                    $brands=['iPhone','iPad','Samsung','Huawei','Nokia','Sony','LG','Motorola','Blackberry','Vodafone','Alcatel','Razer','Google'];

                    # get either the current GET array or an empty array
                    $params=getParams();

                    # add the brands checkboxes
                    foreach( $brands as $brand ){
                        # maintain the checked status by checking if the current brand is in the `brand[]` querystring value
                        $checked=isset( $_GET['brand'] ) && in_array( $brand, $_GET['brand'] ) ? ' checked' : '';

                        # print the checkbox
                        printf('<input type="checkbox" name="brand[]" value="%1$s"%2$s>%1$s<br />', $brand, $checked );
                    }
                ?>
                <!-- a hidden field will ensure the page variable is set each time the form is submitted -->
                <input type='hidden' name='page' value='<?=isset( $_GET['page'] ) ? $_GET['page'] : 1;?>' />
                <input type='submit' />
            </fieldset>
            <fieldset id='paging'>
            <?php

                # some pseudo paging links... should be derived dynamically ~ this is just for demo
                for( $i=1; $i <= 10; $i++ ){

                    $params['page']=$i;
                    $active=isset( $_GET['page'] ) && intval( $_GET['page'] )==$i ? ' class="active"' : '';

                    printf('<a href="?%2$s" %3$s>[ %1$d ]</a>', $i, buildQuery( $params ), $active );
                }           
            ?>
            </fieldset>
        </form>
    </body>
</html>

【讨论】:

  • 这听起来很不错,感谢您快速而详细的回复。我将尝试实现它并看看它是如何工作的。谢谢!
  • 再次感谢您。我已经能够理解您的代码逻辑并根据我的需要进行调整。我对结果很满意
  • 很高兴能够为您提供一些帮助。祝你项目的其余部分好运
  • 以防其他人使用此代码,我建议将隐藏输入的值更改为简单的 1 ()。然后每次用户点击“提交”按钮时,他都会转到第一页。否则,如果他在(比方说)第 15 页,然后更改过滤选项以便只有 14 页或更少,他仍将在第 15 页,并且它将是空白的。
猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
相关资源
最近更新 更多