在Mysql查询的“while”循环中为PHP创建分页

时间:2018-01-13 08:53:01

标签: php mysql twitter-bootstrap while-loop pagination

所以经过3天尝试各种指南后,我仍然无法弄清楚,没有任何作用。我对php的了解并不是那么好,所以这是我求社区帮助的方式。

我需要的只是我的搜索页面的简单分页,它向mysql发送查询并在while循环中打印结果(下面的原始代码):

有什么想法吗?或者我应该更改我的搜索页面?我应该使用一些插件吗?

PS。网站不使用任何cms,它全部用手写。

include("$root/php/connection.php");
    $query=$_GET['s'];
    $results=0;
    $query = htmlspecialchars($query);
    $query = mysqli_real_escape_string($link, $query);
    $exploded_search = explode(" ", $query);

    // this is the code for multiple words on search query
    for($i = 0; $i < count($exploded_search); $i++){
        /* DEBUG */
        /*echo "Piece $i = $exploded_search[$i] <br />";*/


    $sql="SELECT * FROM table_name WHERE CONCAT(name, ' ', address, brand) LIKE '%$exploded_search[$i]%'";
    $data=mysqli_query($link, $sql);

    $dataarray=array();

    $index=1;

    while($row = mysqli_fetch_assoc($data))
        {
            $dataarray[$index] = $row;
            $name = $dataarray[$index]['name'];
            $address = $dataarray[$index]['address'];
            // .... assigning here variables from query, not relevant

            // Here is a chunk of code that is irrelevant to the question


            echo    
            // here i echo the results of the query



            $index++;
            $results++;
        }

    }

1 个答案:

答案 0 :(得分:0)

您应该保留当前页面,并在要求时请求下一页。这是我可以与您分享的简单查询。这里没有安全检查。我使用了$ _REQUEST,因此它处理GET和POST方法

<?php
    $page = $_REQUEST['page']; // which page requested?
    $q = $_REQUEST['q']; // the keyword
    $count = 10; // how many results do you want to return?

    $data = array(); // create an empty array

    if ($r = mysql_query("SELECT * FROM my_table WHERE title like '%$q%' LIMIT $page, $count")) {
        // here you can set your array
        $i = 0;
        while ($d = mysql_fetch_array($r)) {
            $data[$i] = $d;
            $i++;
        }
    }

    if (count($data) > 0) {
        // you have search results... Now do your coding here...
    }
?>