【问题标题】:PHP - Search with PaginationPHP - 分页搜索
【发布时间】:2020-09-21 03:02:39
【问题描述】:

所以我有这两个 PHP 文件 products.php 和 receive.php 。
我的问题是我想使用 Ajax 来显示带有搜索和分页的产品。下面的代码虽然有效,但前提是我使用 GET。
是否可以仅提交页码并仅刷新 div(产品循环的地方)而不是整个页面,以便我的 POST 请求(来自搜索值 -标题,关键字)还会保留吗?因为如果我在分页上使用 GET,点击第二页后 POST 请求会变空。

receive.php

$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';

/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;

// Get Page Number
if(!empty($_GET["page"])) {
    $page = $_GET["page"];
    $start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows  
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
    
    $total_links=ceil($row_count/ROW_PER_PAGE);
    $previous_link = $next_link = $page_link = '';

    if($total_links > 4)
    {
      if($page < 5)
      {
        for($count = 1; $count <= 5; $count++)
        {
          $page_array[] = $count;
        }
        $page_array[] = '...';
        $page_array[] = $total_links;
      }
      else
      {
        $end_limit = $total_links - 5;
        if($page > $end_limit)
        {
          $page_array[] = 1;
          $page_array[] = '...';
          for($count = $end_limit; $count <= $total_links; $count++)
          {
            $page_array[] = $count;
          }
        }
        else
        {
          $page_array[] = 1;
          $page_array[] = '...';
          for($count = $page - 1; $count <= $page + 1; $count++)
          {
            $page_array[] = $count;
          }
          $page_array[] = '...';
          $page_array[] = $total_links;
        }
      }
    }
    else
    {
      for($count = 1; $count <= $total_links; $count++)
      {
        $page_array[] = $count;
      }
    }
    
    for($count = 0; $count < count($page_array); $count++)
    {
      if($page == $page_array[$count])
      {
            // Current Page = Selected Page
        $page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
    
        $previous_id = $page_array[$count] - 1;
        if($previous_id > 0)
        {
            // Previous Button Enable 
            $previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
        }
        else
        {
            // Previous Button Disabled 
            $previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
        }
        $next_id = $page_array[$count] + 1;
        if($next_id > $total_links)
        {
            // Next Button Disabled
            $next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
        }
        else
        {
            // Next Button Enabled

                $next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
        }
      }
      else
      {
        if($page_array[$count] == '...')
        {
            // Ellipsis 
            $page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
        }
        else
        {
            // Pages 
             $page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
        }
      }
    }
    
    $per_page_html .= '<div class="text-center paginate">';
    $per_page_html .= $previous_link . $page_link . $next_link;
    $per_page_html .= '</div>';

}

$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();

products.php

            <div class="row">
                <div class="col">
                    <div class="products_container grid" id="refresh">
                        <?php
                        if(!empty($pdo_result)) { 
                            foreach($pdo_result as $pdo_row) {

                                $id = $pdo_row['id'];
                                $name = $pdo_row['item_title'];
                                $img = $pdo_row['item_img'];
                                $price = $pdo_row['item_price'];
                                $sold = $pdo_row['item_sold'];
                                $stocks = $pdo_row['stocks'];
                                $date = $pdo_row['date'];

                                if ($sold >= $max && $date != date("Y-m-d") ) {
                                    $sort = 'hot';
                                }else if($date == date("Y-m-d") && $sold <= $max){
                                    $sort = 'new';
                                }else{
                                    $sort = '';
                                }
                                echo '
                                <div class="product grid-item '.$sort.'">
                                    <div class="product_inner">
                                        <div class="product_image">
                                            <a href="item.php?prod='.$id.' "><img src="'.$img.'" alt=""></a>
                                            <div class="product_tag">'.$sort.'</div>
                                        </div>
                                        <div class="product_content text-center">
                                            <div class="product_title text-long"><a href="item.php?prod='.$id.' ">'.$name.'</a></div>
                                            <div class="product_price">₱'.number_format($price).'</div>
                                            <div class="product_button ml-auto mr-auto trans_200">
                                                <button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button> 
                                            </div>
                                        </div>
                                    </div>  
                                </div>
                                ';
                            } //End Foreach Loop
                        }
                        else{
                            echo "no products found";
                        }
                    ?>
                    </div>
                </div>
            </div>
            <!-- PAGINATION HERE -->
            <?php echo $per_page_html; ?>

【问题讨论】:

  • 搜索不应通过 POST 完成
  • 哦,我明白了,如果我在搜索中使用 GET 会更好吗?因为我的搜索功能也有价格范围和一些复选框。可以吗?
  • 检查 HTTP 方法描述。 POST 仅在更改数据时使用。要获取数据、过滤器等,请使用 GET

标签: php jquery mysql ajax


【解决方案1】:

方法一 => 无ajax

您也可以使用 GET 方法来搜索值。并且在每个分页链接中 也附加搜索值。
例如。

$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
        

而不是上面一行使用下面的一行。

$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';


方法 2 => 使用 ajax
而不是 href 使用 javascript function 如下所示

$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'


<script>
  function paginate_fn(pageID, keyword){
        $.ajax({
            async: true,
            type: 'get', // you can use post also 
            dataType:'json',
            data: {'pageID':pageID, 'keyword': keyword},
            url: "paget_name.php", // your page name            
            success: function (data) {
                $('#search-content').html( data['content'] );
            },
            error: function () {
                alert('An Error Occurred!.');
            }
        });
    }
</script>

【讨论】:

  • 好吧,我认为方法 1 可能不错,因为我还有其他搜索输入,例如价格范围和类别(复选框)。如果我的网址那么长,可以吗?例如,如果我对所有搜索过滤器都重视? ` products.php?page='.$next_id.'&search='.$keyword.'&category='.$category[0].'&category='.$category[1].'&minimum='.$minimum. '&maximum='.$maximum.' `
  • 有一个限制,但这远非如此。
  • 什么是限制?关于 url 和 GET 参数?
  • 哦,我明白了,好吧,我想我不会达到那么多,而且限制是每个参数的权利,而不是专门限制查询参数,如 ?category[0]=1&amp;category[1]=3&amp;category[2]=19
猜你喜欢
  • 2013-07-25
  • 2013-11-11
  • 1970-01-01
  • 2017-03-25
  • 2019-06-30
  • 1970-01-01
  • 2017-10-30
  • 2013-08-29
  • 1970-01-01
相关资源
最近更新 更多