php分页和搜索

时间:2013-07-25 15:20:14

标签: search loops pagination while-loop

我有一个分页的循环我有我的想法如何进行搜索只是不知道如何插入这里我的代码分页和输出命令工作只是不知道如何把代码搜索而且它让我头疼。

//Count the total number of row in your table*/
$count_query   = mysql_query("SELECT COUNT(personid) AS numrows FROM persons");
$row     = mysql_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows/$per_page);
$reload = 'index.php';
//main query to fetch the data 
$query = mysql_query("SELECT * FROM persons ORDER by RAND() LIMIT $offset,$per_page");
//loop through fetched data
while($result = mysql_fetch_array($query)){
$id = $result['PersonID'];
echo "<div class= content > ";
echo"<img height=100 width=100 src='upload/". $result['Image'] ."'/>";
echo "<font color='black'>". $result['FirstName']. "</font></br>";
echo "</div>";

因此我做了试验和错误我认为我得到错误的部分是这里的行是我的整个代码

> <?php include_once('includes/dbConnect.php');
> 
> 
> ?>
> 
> <?php
> 
> // now you can display the results returned. But first we will display
> the search form on the top of the page
> 
> $searchText = $_POST["q"];
> 
> 
> 
> 
> 
> $action = (isset($_REQUEST['action'])&& $_REQUEST['action']
> !=NULL)?$_REQUEST['action']:'';
> 
> if($action == 'ajax'){
> 
>   include 'pagination.php'; //include pagination file
> 
> 
>   //pagination variables  $page = (isset($_REQUEST['page']) &&
> !empty($_REQUEST['page']))?$_REQUEST['page']:1;   $per_page = 5; //how
> much records you want to show     $adjacents  = 5; //gap between pages
> after number of adjacents     $offset = ($page - 1) * $per_page;
> 
>   //Count the total number of row in your table*/     $count_query   =
> mysql_query("SELECT COUNT(personid) AS numrows FROM persons");    $row  
> = mysql_fetch_array($count_query);    $numrows = $row['numrows'];     $total_pages = ceil($numrows/$per_page);    $reload = 'index.php';
> 
>                   //search
>         // basic SQL-injection protection
> 
>         $searchText = $_REQUEST["q"];     //main query to fetch the data
>         // query with simple search criteria $query = mysql_query("SELECT * FROM persons WHERE FirstName LIKE '%"
>            . $searchText . "%' ORDER by RAND() LIMIT $offset,$per_page");
> 
>   //loop through fetched data
> 
> 
>         while($result = mysql_fetch_array($query)){
>         $id = $result['PersonID'];
> 
> 
>                                       echo "<div class= content > ";
> 
>                                       echo"<img height=100 width=100 src='upload/". $result['Image'] ."'/>";
>                                       echo "<font color='black'>". $result['FirstName']. "</font></br>";
> 
> 
> 
>                                       echo "</div>";
> 
> 
> } echo paginate($reload, $page, $total_pages, $adjacents); } else{ ?>
> 
> 
> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Simple Ajax
> Pagination With PHP And MySql</title> <script type="text/javascript"
> src="jquery-1.5.2.min.js"></script> <link media="screen"
> href="style.css" type="text/css" rel="stylesheet"> <script
> type="text/javascript">   $(document).ready(function(){       load(1);    });
> 
>   function load(page){        $("#loader").fadeIn('slow');        $.ajax({
>           url:'index.php?action=ajax&page='+page,             success:function(data){
>               $(".outer_div").html(data).fadeIn('slow');
>               $("#loader").fadeOut('slow');           }       })
> 
>         }
> 
> </script>
> 
> </head> <body>
>  
> 
> 
> <div id="loader"><img src="loader.gif"></div>
> 
> 
> 
> <div class="outer_div"></div>
> 
>     <div class="content"><form action='' method='POST'> <input type='text' name='q' /> <INPUT TYPE="button" onClick="history.go(0)"
> VALUE="Refresh"/> </p> </form></div> </body> </html> <?php
> 
> }?>

这是我想要的输出 1:http://i.stack.imgur.com/l8MMA.png
2:http://i.stack.imgur.com/p47UI.png

2 个答案:

答案 0 :(得分:1)

因此,一种方法可能是将explode字符串转换为令牌,然后将其作为like命令放入查询中:

$sql = "SELECT * FROM persons WHERE ";

$tokens = explode(" ", $searchText);
if (count($tokens) == 0) {
    $sql += "1 = 1"
}
else {
    $i = 0;
    foreach ($tokens as $val) {
        if ($i > 0) {
            $query += " OR ";
        }
        $i++;
        $query += "(firstname LIKE '%$val%' OR lastname LIKE '%$val%')";
    }
}

$sql += " ORDER by RAND() LIMIT $offset, $per_page";

$query = mysql_query($sql);

注意:我将查询保持为SQL注入状态。主要是因为我不想重写它以使用mysqli。这是你需要做的事情。您需要一个存在令牌数量的计数器,并且您将参数命名为$token1$token2等。

答案 1 :(得分:1)

在您的情况下,您可以简单地添加带有模式条件的WHERE子句并快速获得所需的效果。

// basic SQL-injection protection
$searchText = htmlspecialchars ($_POST['searchText']);

// query with simple search criteria
$query = mysql_query("SELECT * FROM persons WHERE FirstName LIKE '%" 
           . $searchText . "%' ORDER by RAND() LIMIT $offset,$per_page");

但这种观点有几个不足之处:

  1. 您的请求非常慢(您将在数据库中看到更多数据),因为您使用ORDER BY RAND()构造在DB表中随机排序所有条目,然后返回指定的少量数据在你的LIMIT条款中;
  2. 每次要搜索某些内容时重新加载页面都是必要的。如果要实现搜索结果列表的动态更新,则应使用Javascript中的AJAX个查询。
  3. P.S。:尽量不要使用已弃用的mysql_函数,使用PDOmysqli indstead(它们通过准备好的语句提供内置的SQL注入保护)。

    <强>更新

    好的,你已经在使用AJAX了。

    所以你根本不需要表格。使用2个元素:文本输入和按钮。

    HTML:

    <input id="q" type='text' name='q' />
    <input type="button" onClick="load(1)" value="Refresh"/>
    

    使用Javascript:

    function load(page){
        $("#loader").fadeIn('slow');
        var searchText = $('#q').val();
        $.ajax({
               url:     'index.php?action=ajax&page='+page+'&q='+searchText, 
               success:  function(data){
                   $(".outer_div").html(data).fadeIn('slow');
                   $("#loader").fadeOut('slow');           
               }
        });
    }