In PHP, I'm trying to implement pagination that displays different results from a SQL database based off LIMIT. I know how to write pagination with multiple parameters but I'm unsure of how to code the application to recognize the second condition for the SQL interjection.
If you look at the code where it contains the foreach
and the href containing page_number and category_id
I need to get the pagination at the bottom to adhere to which category picked within the foreach
to display the correct data. Also I couldn't figure out how to implement the pages without hardcoding within the for loop
This is the function for the SQL query page
function get_products_by_category($category_id, $pn)
{
global $db;
$arithmetic = 8*($pn -1);
$query = "SELECT * FROM products
WHERE products.categoryID = :category_id
ORDER BY productID LIMIT $arithmetic, 8";
$statement = $db->prepare($query);
$statement->bindValue(":category_id", $category_id);
$statement->execute();
$products = $statement->fetchAll();
$statement->closeCursor();
return $products;
}
Here's where it gets called
if ($action == 'list_products')
{
$category_id = filter_input(INPUT_GET, 'category_id',
FILTER_VALIDATE_INT);
if ($category_id == NULL || $category_id == FALSE)
{
$category_id = 1;
}
$category_name = get_category_name($category_id);
$categories = get_categories();
$products = get_products_by_category($category_id, $pn);
$products_amount = get_products_total($category_id);
$total = count($products_amount);
include('product_list.php');
}
Here's the foreach and pagination
<?php
$pn;
$current_category;
$total_page = $total/8;
$remain = $total % 8;
if($remain > 0)
{
$total_page = $total_page + 1;
}
?>
<aside>
<!-- display a list of categories -->
<h2>Categories</h2>
<nav>
<ul>
<?php foreach ($categories as $category) : ?>
<li>
<a href="?category_id=<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName'];?>
</a>
</li>
<?php endforeach; ?>
for($i = 1; $i <= $total_page; $i++)
{
?>
<a href="?page_number= <?php echo $i; ?> & ?category_id= <?php echo $i; ?>"><?php echo $i; ?> </a>
<?php
if($i == 1)
{
$pn = 1;
}
else if($i == 2)
{
$pn = 2;
}
else if($i == 3)
{
$pn = 3;
}
}
?>
Try this:
<a href="?page_number=<?php echo $i; ?>&category_id=<?php echo $category_id; ?>"><?php echo $i; ?> </a>