Am I doing this right? I do not know how to properly connect functions with pagination. To make everything work, I have to duplicate this variables. When I add variables to the function and to the index, then everything works.
$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;
Function
function find_all_products_by_cat_id2($cat_id, $options=[]) {
global $db;
$visible = $options['visible'] ?? false;
$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;
$sql = "SELECT * FROM products ";
$sql .= "WHERE cat_id='" . db_escape($db, $cat_id) . "' ";
if($visible) {
$sql .= "AND visible = true ";
}
$sql .= "ORDER BY prod_name ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
index.php
<?php
$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;
$category_id = $_GET['id'] ?? 1;
$products_count = count_products_by_cat_id($category_id, ['visible' => true]);
if(isset($_GET['id'])) {
$category_id = $_GET['id'];
$product_set = find_all_products_by_cat_id2($category_id, ['visible' => true]);
if(!$product_set) {
redirect_to(url_for('/index.php'));
}
$product_count = mysqli_num_rows($product_set);
if($product_count == 0) {
echo "<h1>No more products</h1>";
}
?>
I think I found a solution.
Update 1
Function
function find_by_sql($sql) {
global $db;
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
index.php
$visible = $options['visible'] ?? false;
$sql = "SELECT * FROM products ";
$sql .= "WHERE cat_id='" . db_escape($db, $category_id) . "' ";
if($visible) {
$sql .= "AND visible = true ";
}
$sql .= "ORDER BY prod_name ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";
$product_set = find_by_sql($sql, ['visible' => true]);