基于某些条件的PHP分页

时间:2018-08-12 00:13:23

标签: php mysql arrays pagination

我是PHP新手。我有一个显示壁纸的android应用。以下PHP脚本在分页中将数据从``最新''返回到``最旧''。它工作正常,但问题是无论条件如何,总是从头开始收集行。例如,如果我要检索类别ABSTRACT从最新到最旧的壁纸,它以最后一个ID开头并忽略该类别并给出错误的结果。 这就是我想要的。

  1. 获取基于某些类别的壁纸
  2. 将结果存储在某个数组中
  3. 在给定页码中从该数组计算变量和从该变量计算
  4. 发回结果

我希望你们了解我真正想要做的。请帮助我。

<?php

$conn = new mysqli('server', 'abc', '123', 'Walls');

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$page_number = $_POST["page_number"];
$item_count = 40;


$r = mysqli_query($conn, "SELECT * from wallpaper_info order by id desc 
limit 1;");
$row = mysqli_fetch_array($r);
$total = $row[0];


$page_limit = ($total/$item_count) - $page_number; 

$from = $page_limit * $item_count - ($item_count - 1);
$to = $page_limit * $item_count;

$response = array();
$status = array();

if($page_limit <= 0){

array_push($response,array('status'=>'end'));
echo json_encode($response);

}else{

array_push($response,array('status'=>'ok'));

//Working fine
$mysql_query = "select * from wallpaper_info where id BETWEEN $from AND $to 
order by id desc;";
//Not working
$mysql_query = "select * from wallpaper_info where id BETWEEN $from AND $to 
and category = 'Abstract' order by id desc;";

$results = mysqli_query($conn,$mysql_query);

$wallpapers = array();

while($row = mysqli_fetch_array($results)){

array_push($wallpapers,
array(

'id'=>$row[0],'name'=>$row[1],'category'=>$row[2],'thumb_url'=>$row[3],'img_ 
 url'=>$row[4],'size'=>$row[5],'downloads'=>$row[6],'views'=>$row[7]

));
}

array_push($response,array('wallpapers'=>$wallpapers));
echo json_encode($response);
mysqli_close($conn);
}

?>

1 个答案:

答案 0 :(得分:-1)

$mysql_query = "SELECT * FROM `wallpaper_info`
                WHERE category = 'Abstract'
                ORDER BY id DESC
                LIMIT 10 OFFSET 0
                 ";

https://www.w3schools.com/sql/sql_top.asp很好的例子

对于页码,您可以尝试以下操作:

<?php
$pagesize = 10;//LIMIT
$offset = 0;//OFFSET

//pdo query example.. 
$sql = "SELECT FOUND_ROWS();"
$totall_rows = $conn->query($sql)->fetchColumn(0);

$calc_pages = ceil($totall_rows / $pagesize);
$last_row_number = $pagesize + $offset - 1;

if ($last_row_number >= $totall_rows)
     $last_row_number = $totall_rows - 1;
if ($totall_rows > 0)
     $current_page = ceil(( $calc_pages * ($offset + 1)) / $totall_rows );
?>
<form method="GET" enctype="application/x-www-form-urlencoded" action="">
Page: 
<input type="submit" value="<?php echo "< ";echo($current_page - 1);?>">
<?php echo "<b>$current_page</b>/$calc_pages"; ?>
<input type="submit" value="<?php echo($current_page + 1); echo " >";?>">
</form>
<?php 

测试一下,告诉它是否无效