分页搜索

时间:2015-03-22 14:15:32

标签: javascript php mysql ajax mysqli

我的问题是基于这个写得很好的教程: http://www.sanwebe.com/2013/03/loading-more-results-from-database

演示: http://www.sanwebe.com/downloads/43-load-more-results

基本上我正在努力实现这个+搜索。从某种意义上说,将根据用户的搜索查询填充结果。

让我详细说明代码:

这是主页

<?php
include("includes/db.php");




$results = mysqli_query($con,"SELECT COUNT(*) FROM courses");
$get_total_rows = mysqli_fetch_array($results); //total records

//break total records into pages
$item_per_page = 10;
$total_pages = ceil($get_total_rows[0]/$item_per_page); 

?>
<html>
<head>

    <script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>

<script>
$(document).ready(function() {

    var track_click = 0; //track user click on "load more" button, righ now it is 0 click

    var total_pages = <?php echo $total_pages; ?>;

    $('#results').load("fetch_pages.php", {'page':track_click}, function() {track_click++;}); //initial data to load


    $(".load_more").click(function (e) { //user clicks on button

        $(this).hide(); //hide load more button on click
        $('.animation_image').show(); //show loading image

        if(track_click <= total_pages) //user click number is still less than total pages
        {
            //post page number and load returned data into result element
            $.post('fetch_pages.php',{'page': track_click}, function(data) {

                $(".load_more").show(); //bring back load more button

                $("#results").append(data); //append data received from server

                //scroll page smoothly to button id
                $("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);

                //hide loading image
                $('.animation_image').hide(); //hide loading image once data is received

                track_click++; //user click increment on load button

            }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
                alert(thrownError); //alert with HTTP error
                $(".load_more").show(); //bring back load more button
                $('.animation_image').hide(); //hide loading image once data is received
            });


            if(track_click >= total_pages-1) //compare user click with page number
            {
                //reached end of the page yet? disable load button
                $(".load_more").attr("disabled", "disabled");
            }
         }

        });
});
</script>
</head>
<body>
    <center>
    <form method="get" action="testSearch.php" enctype="multipart/form-data" autocomplete="off">
<input type="text" class="search" id="searchid" name="user_query" id="searchBar" placeholder="Search for courses" />
          <input type="submit" id="searchButton"  name="search" value="search" class="btn btn-danger" autocomplete="off"/>
<div id="results"></div>
<div align="center">
<button class="load_more" id="load_more_button">load More</button>
<div class="animation_image" style="display:none;"><img src="ajax-loader.gif"> Loading...</div>
</div>

</body>
</html>

这是fetch_page.php,基本上是从以下位置填充内容的地方:

<?php
include("includes/db.php"); 

//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
  header('HTTP/1.1 500 Invalid page number!');
  exit();
}
$item_per_page = 10;
//get current starting point of records
$position = ($page_number * $item_per_page);

//Limit our results within a specified range. 
$results = mysqli_query($con,"SELECT course_title, course_date1, course_provider,course_sdesc FROM courses ORDER BY course_date1 DESC LIMIT $position, $item_per_page");

//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
  echo '<li id="item_'.$row["course_title"].'"><span class="page_name">'.$row["course_date1"].') '.$row["course_provider"].'</span><span class="page_message">'.$row["course_sdesc"].'</span></li>';
}
echo '</ul>';
?>

现在深入了解详情:

以下是允许搜索发生的表单(在索引页面的内容中):

<form method="get" action="testSearch.php" enctype="multipart/form-data" autocomplete="off">
    <input type="text" class="search" id="searchid" name="user_query" id="searchBar" placeholder="Search for courses" />

我想做的事情,我没有取得如此成功的是以下几点: 在主页面的标题中(在计算分页的页面代码中):我正在考虑进行以下更改:

 if(isset($_GET['user_query']))
    {

 $search_query = $_GET['user_query'];
$results = mysqli_query($con,"SELECT COUNT(*) FROM courses where course_title like '%$search_query%'");
$get_total_rows = mysqli_fetch_array($results); //total records

//break total records into pages
$item_per_page = 10;
$total_pages = ceil($get_total_rows[0]/$item_per_page); 
}
?>

如果尝试在fetch页面中也通过将代码调整为以下内容来执行相同的操作:

  <?php
include("includes/db.php"); 

  if(isset($_GET['user_query']))
    {

       $search_query = $_GET['user_query'];

//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
  header('HTTP/1.1 500 Invalid page number!');
  exit();
}
$item_per_page = 10;
//get current starting point of records
$position = ($page_number * $item_per_page);

//Limit our results within a specified range. 
$results = mysqli_query($con,"SELECT course_title, course_date1, course_provider,course_sdesc FROM courses ORDER BY course_date1 where course_title like '%$search_query%' DESC LIMIT $position, $item_per_page");

//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
  echo '<li id="item_'.$row["course_title"].'"><span class="page_name">'.$row["course_date1"].') '.$row["course_provider"].'</span><span class="page_message">'.$row["course_sdesc"].'</span></li>';
}
echo '</ul>';
}
?>
然后没有任何反应。

我认为问题在于我试图从另一个页面的url中检索变量。换句话说,fetch_page.php正试图从testSearch.php中检索user_query =,我不知道如何解决它。

新方法: 我把它放到了现场,所以你可以知道我想要做什么: http://testapplication220-env.elasticbeanstalk.com/testSearch.php

在testSearch.php(主页上,我这样做是为了获取用户搜索查询并稍后检索它)。

session_start();

 $search_query = $_GET['user_query'];
 $_SESSION['userSearch'] = $search_query;
$results = mysqli_query($con,"SELECT COUNT(*) FROM courses where course_title like '%$search_query%'");

然后获取页面(功能,我尝试执行以下操作):

session_start();
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
  header('HTTP/1.1 500 Invalid page number!');
  exit();
}
$item_per_page = 10;
//get current starting point of records
$position = ($page_number * $item_per_page);

//Limit our results within a specified range. 
$results = mysqli_query($con,"SELECT course_title, course_date1, course_provider,course_sdesc FROM courses ORDER BY course_date1 where course_title like '%$_SESSION['userSearch']%' DESC LIMIT $position, $item_per_page");

1 个答案:

答案 0 :(得分:0)

我想我得到了答案

如果页面变量不包含数字,则抛出500错误。

使用filter_var函数从post数组中转义页面变量

但根据php.net filter_var只会验证数据不会将其转换为否。我在phpfiddle中测试它也返回字符串。

var_dump(filter_var('23',FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH));

所以在通过is_numeric比较页面之前,你必须将它转换成可以通过以下方式完成的整数

$page = (int) $page;