首页 > 解决方案 > 如何在php中结合分页和过滤?

问题描述

我想显示数据库中的一些产品并使用分页以及复选框进行过滤。我的分页工作正常。当我单击复选框并按“提交”时,我确实会在第一页上得到过滤结果。但是,当我移至第二页或任何其他页面时,复选框会自动变为未选中状态,并且过滤会丢失。这是我的 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”之类的想法,但我不知道如何实现它。因此,如果您更具体,我将非常感激。非常感谢!

标签: phpdatabasecheckboxpaginationfiltering

解决方案


如果您要使用 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>

推荐阅读