我正在尝试将搜索结果添加到分页中。我迷路了-我尝试了几乎所有组合。这是我未解决的问题-如果搜索结果为“ wlo”-有2页(计数11个结果),但是如果我单击Next或2-将显示所有结果。 http://Test site
代码index.php
<?php
$search_statement = isset($_POST['search']) ? $_POST['search'] : '';
$search = db_escape($db, $search_statement);
$sql1 = "SELECT * ";
$sql1 .= "FROM products ";
$sql1 .= "WHERE (`prod_name` LIKE '%".$search."%') ";
$products_sql_count = mysqli_query($db, $sql1);
$products_count = mysqli_num_rows($products_sql_count);
mysqli_free_result($products_sql_count);
$rowperpage = 10;
$page = isset($_GET['page']) ? $_GET['page'] : '1';
$page = $page - 1;
$p = $page * $rowperpage;
$search_statement = isset($_POST['search']) ? $_POST['search'] : '';
$search = db_escape($db, $search_statement);
$sql = "SELECT * ";
$sql .= "FROM products ";
$sql .= "WHERE (`prod_name` LIKE '%".$search."%') ";
$sql .= "ORDER BY cat_id ASC, position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";
$products_set = mysqli_query ($db, $sql);
echo $sql;
链接
<?php
echo '<br />';
$page_nb = isset($_GET['page']) ? $_GET['page'] : '1';
$check = $p + $rowperpage;
if($products_count > $check) {
$next_page = $page_nb + 1;
echo "<a href='index.php?page=".$next_page."&".$search."'>Next</a> ";
}
$limit = $products_count / $rowperpage;
$limit = ceil($limit);
for($i = max(1, $page_nb - 5); $i <= min($page_nb + 5, $limit); $i++){
echo "<a href='index.php?page=".$i."&".$search."'>".$i." </a> " ;
}
if($page_nb > 1) {
$prev_page = $page_nb - 1;
echo "<a href='index.php?page=".$prev_page."&".$search."'>Back</a>";
}
echo '<br /><br />';
?>
答案 0 :(得分:0)
您还需要在查询字符串中传递搜索字符串。更改代码如下:
echo "<a href='index.php?page=".$prev_page."&search=".$search."'>Back</a>";
请根据上述内容在所有行中进行更改。另外,您需要在seacrh字符串的PHP代码中进行如下更改:
$search_statement = isset($_POST['search']) ? $_POST['search'] : '';
if ($search_statement == '') {
$search_statement = isset($_GET['search']) ? $_POST['search'] : '';
}
而且我认为您仅应在存在以下任何搜索字符串时将搜索字符串内容应用于以下位置:
$sql = "SELECT * ";
$sql .= "FROM products ";
if ($search != '') {
$sql .= "WHERE (`prod_name` LIKE '%".$search."%') ";
$search = db_escape($db, $search_statement);
}
$sql .= "ORDER BY cat_id ASC, position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";
希望它对您有帮助。
答案 1 :(得分:0)
您的第一个问题是使用POST
,您应该使用GET
,即将$_POST
更改为$_GET
,并将method="post"
更改为method="get"
在您的<form>
HTML标记中,或者删除方法属性,因为GET是默认属性。
第二个问题是在链接中添加搜索参数的方式,您当前正在做&{$search}
,而您应该做&search={$search}
或者将其保留为与"&search=" . $search . "
相同的格式。
请记住,此代码是不好的做法,并且很容易受到SQL注入的影响,请查看适用于PHP的PDO API。