Paginate a category page

Hello! I have this script below listing items from a table by their cat IDs. Since it’s already filtering results by a cat_id, is it possible to paginate the results like this? http://code.runnable.com/U8dzQWEzMxxqeQ_E/php-pagination-example-using-mysql-database-for-dbms

<?php

if(isset($_GET['cat'])){
  $cat_id = sanitize($_GET['cat']);
}
else {
  $cat_id = '';
}
$sql = "SELECT * FROM properties WHERE categories = '$cat_id'";
$propertiesQ = $db->query($sql);
$category = get_category($cat_id);
?>

<?=$category['parent']. ' / ' .$category['child'];?>
<br>
<br>
<?php while($property = mysqli_fetch_assoc($propertiesQ)): ?>
<?php $images = explode(',',$property['image']); ?>


<img style="width:200px;" src="<?=$images[0];?>">
<br>
<?= $property['title']; ?>
<br>

<br>
<br>
<?php endwhile; ?>

It is certainly possible to paginate the results. I wouldn’t use the code in the link you supplied because that uses the old-style mysql calls that aren’t part of the language any more, but that doesn’t stop you taking the key principles - passing in the page number, using that to add the LIMIT clause into the query, and drawing the links for the user to page forward and backwards.

1 Like

Okay, I’ve tried what you said but now it doesn’t show the records in the table. There isn’t any error message either.

$pages=10;
if(isset($_GET['cat'])){
  $cat_id = sanitize($_GET['cat']);
}
else {
  $cat_id = '';
}
$start = ($cat_id-1) * $pages; 
$sql = "SELECT * FROM properties WHERE categories = '$cat_id' LIMIT $start, $pages";
$propertiesQ = $db->query($sql);
$category = get_category($cat_id);
?>

<?=$category['parent']. ' / ' .$category['child'];?>
<br>
<br>
<?php while($property = mysqli_fetch_assoc($propertiesQ)): ?>
<?php $images = explode(',',$property['image']); ?>


<img style="width:200px;" src="<?=$images[0];?>">
<br>
<?= $property['title']; ?>
<br>

<br>
<br>
<?php endwhile; ?>

<?php 
$sql = "SELECT * FROM properties WHERE categories = '$cat_id'";
$result = $db->query($sql);
$total_records = mysqli_num_rows($result); 
$total_pages = ceil($total_records / $pages); 

echo "<a href='category.php?cat=".$cat_id."?page=1'>".'|<'."</a> "; // Goto 1st page  

for ($i=1; $i<=$total_pages; $i++) { 
            echo "<a href='category.php?cat=".$cat_id."?page=".$i."'>".$i."</a> "; 
}; 
echo "<a href='category.php?cat=".$cat_id."?page=$total_pages'>".'>|'."</a> "; 
?>
1 Like

So here

else {
  $cat_id = '';
}
$start = ($cat_id-1) * $pages; 

Surely that’s going to result in a value of -10 if $cat_id isn’t specified - will that work?

If that’s not it, which query is failing, the first or the second?

1 Like

Meanwhile I figured it out, thank for the reply tho :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.