diff --git a/includes/functions.php b/includes/functions.php index 6403921..e2ceb3f 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -72,7 +72,7 @@ function get_product_price($product) { } /** - * Paginate a query result. + * Paginate a query result. * * @param PDO $pdo The PDO connection object. * @param string $query The base SQL query (without LIMIT/OFFSET). @@ -107,7 +107,9 @@ function paginate_query($pdo, $query, $params = [], $default_limit = 20) { } // Count total rows using a subquery to handle complex queries safely - $count_sql = "SELECT COUNT(*) FROM ($query) as count_table"; + // Strip ORDER BY from the query for the count to avoid SQL errors and improve performance + $count_query = preg_replace('/ORDER\s+BY.*$/is', '', $query); + $count_sql = "SELECT COUNT(*) FROM ($count_query) as count_table"; $stmt = $pdo->prepare($count_sql); $stmt->execute($params); $total_rows = $stmt->fetchColumn();