分页脚本不适用于数据表

时间:2019-05-24 18:52:29

标签: php html css pagination

我已经处理了两天以上的问题,但仍然找不到问题所在。我正在尝试为搜索结果建立一个分页系统。当我在新的php文件中运行代码时,代码工作得很好,但是当要在表中显示这些结果时,我总是不断收到该错误!最后else部分中的消息。另外,无论我在哪里放置循环的页码,它总是显示在表格前。认为我在处理这个问题时非常忙,因此我将注意力集中在同一点上。请帮助!

编辑我刚刚删除了所有条件语句,并获得了我通过POST方法获得的所有变量的未定义索引。这就是问题所在,但仍然不知道该怎么解决。

<?php

if (isset($_POST['search_btn'])) {
include_once "db_connect.php";

$from = $_POST['from'];
$where = $_POST['where'];
$date = $_POST['date'];
$type = $_POST['type'];
$proc_id = $_POST['proc_id'];

if(empty($from) || empty($where) || empty($date) || empty($type)){
header("Location: index.php?search=empty");
exit();
}else{
//define how many results you want per page
$results_per_page = 10;

//number of results stored in database
"SELECT * FROM proc WHERE p_from = '".$from."' and p_where = '".$where."' and type= '".$type."' ";

$result = mysqli_query($conn, $sql);
$number_of_results = mysqli_num_rows($result);

//determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);

//determine which page number visitor is currently on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}

//determine the SQL LIMIT starting number for the result on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;

//retrive selected results from database and display them on page                                   $sql='SELECT * FROM proc LIMIT ' . $this_page_first_result . ',' .  $results_per_page;

$result = mysqli_query($conn, $sql);

while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

echo '<tr onclick="content(\''. $rows['proc_id'] .'\')">';
echo "<td>" .$rows['p_name'] . " " . $rows['p_surname']. " </td>";
echo "<td>" .$rows['p_from']. "</td>";  
echo "<td>" .$rows['p_where']. "</td>";
echo "<td>" .$rows['p_date']. "</td>";  
echo "<td>" .$rows['price']. "</td>";   
echo "<td>" .$rows['type']. "</td>";    
echo "</tr>";

 }
}
//display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
echo '<a href="search.php?page=' . $page . '">' . $page . '</a> ';
                                        }

}else{
echo "Error!";
}

?>

1 个答案:

答案 0 :(得分:2)

我只是假设初始显示有效,但是分页给您带来了麻烦?

您正在使用POST值将数据从搜索表单传递到您的代码,但是,当您单击分页链接时,您将转移到搜索页面,并且丢失这些值。

您可以将下一页URL更改为表单,然后将每个必需的值作为隐藏的输入字段进行传递。但是,这样做的缺点是,当您在浏览器中单击后退按钮时,它将抱怨并要求您重新提交表单数据。

另一种解决方案是将这些post参数存储在会话中,即cookie,无论是什么。但是我认为,这对于解决这个问题也不是一件好事。

我建议您使用GET参数,然后再在下一页按钮中传递这些参数。这具有能够为您的搜索添加书签的额外好处。

祝你好运!


作为旁注,应该使用准备好的语句,而不是使用串联构建查询。有关我在以下转换后的代码中使用的功能的信息,请参见文档:https://www.php.net/manual/en/class.mysqli-stmt.php

    if ($statement = mysqli_prepare($conn, "SELECT * FROM proc WHERE p_from = ? AND p_where = ? AND type = ?")) {
        mysqli_stmt_bind_param($statement, "s", $from);
        mysqli_stmt_bind_param($statement, "s", $where);
        mysqli_stmt_bind_param($statement, "s", $type);

        $result = mysqli_stmt_get_result($statement);
    }