Home > Blockchain >  Is there any way to search from the result in query?
Is there any way to search from the result in query?

Time:09-01

I am making pagination in core PHP (actually first time). As user will press the pagination button for example user pressed second pagination button. then this query generates:

SELECT * FROM product LIMIT 12, 12

It is executing perfectly as I expected. but the main problem is that if user wants to do filtration on that specific page for suppose user wants all items which are present in page 2 and category_id must be 3 then this query generates:

SELECT * FROM products WHERE category_id IN (3) LIMIT 12, 12 

But I am getting the empty resultset... What I am doing wrong?

CodePudding user response:

The pages are based on the number of lines your query returns. You cannot apply a filter on a single page on the DB side as any additional Wheres would change the elements in the pages of the previous query.

In your case, adding WHERE category_id IN (3) results in no lines, making your new page empty.

You could implement filters in your frontend, or backend AFTER the query returns the result, and your filter would remove items from the DB result.

Ideally, every time your users interact with the UI, it would result in a new call to the DB with the filters being applied on the query. then show the result to your user.

CodePudding user response:

If I understood correctly you want to change the WHERE clause in any way between pages and you not want any previous records be repeated.

If you have a unique id in your table and that id increases with each page you can use for a bookmark. I have a simple procedure to make that column. Then you can create a column specifically for this app.

You create a bookmark column and add it to the WHERE clause.
This column will give you a bookmark to save the user's position.
You save this column's value from the last record.
Then in your query you can add this position your query in the WHERE clause

WHERE `bookmark` > $position AND ...

Then you can make any change between any pages at any time you want to the WHERE clause and you will never repeat a previous record.

Making this new column is very simple and does not require much storage.
Use the same ORDER BY from your page query and make your WHERE 1.

$sql = SELECT `product_id` FROM `products`  WHERE 1  ORDER BY `category`, `description`"; 
$results = mysqli_query($conn,$sql);
while(list($product_id) = mysqli_fetch_array($results, MYSQLI_NUM)){
  $bookmark[] = $product_id;
}

foreach($bookmark as $position => $product_id){
$sql = "UPDATE `products` SET `bookmark` = $position WHERE `product_id`=$product_id";
}
  • Related