简体   繁体   中英

How can I combine pagination and filtering in php?

I would like to display some products from database and use pagination as well as checkboxes for filtering. My pagination is working fine. And when I click checkboxes and press "submit," I do get filtered results on the first page. However, when I move to the second or any other page, the checkboxes automatically become unchecked and the filtering gets lost. Here is my HTML code:

<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';?>

My pagination is made this way:

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> ';
  }
}

In order to apply filtering I use an IF statement:

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

I assume that when I go to the next page, my checkboxes get unchecked, this $_GET['brand'] becomes empty and the "else" statement is activated. I tried to find solutions for this problem, but some of them were not effective and some were too hard for me to understand (I am a beginner). Could you please explain in simple terms how to keep the checkboxes checked and how to keep the filtering throughout all the pages? I saw such ideas as "use session" or "keep the data in url," but I can't figure out how to implement it. So if you are more specific, I would be super grateful. Thank you very much!

If you were to use PHP to generate the brands checkboxes ( something that has merit if there are many brands which can be altered any time by an administrator for example ) then perhaps the following might give an idea how to maintain the checked status of each checkbox.

The following is a rough idea how you might accomplish the stated goal - I hope you might find it of help.

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM