0

I am making an infinite scroll app in which records from database will be fetch. When the user clicks "Load More" button a function is called for retrieving data from database.

My problem is that when I am running this(below) query every Time I am getting the same records.

SELECT ArticleTitle, PreviewText, PreviewImage FROM Articles ORDER BY ID DESC LIMIT 4 

regards....

Tech guy
  • 125
  • 1
  • 8

2 Answers2

1

You've to use the OFFSET and LIMIT together like this.

Explanation: The OFFSET value is also most often used together with the LIMIT keyword. The OFF SET value allows us to specify which row to start from retrieving data. By the way you can also omit the OFFSET keyword and use like this LIMIT 0,4 which tells to get 4 rows starting from 0. see more

SELECT ArticleTitle, PreviewText, PreviewImage 
FROM Articles 
ORDER BY ID DESC LIMIT 4 OFFSET 0 

SELECT ArticleTitle, PreviewText, PreviewImage 
FROM Articles 
ORDER BY ID DESC LIMIT 4 OFFSET 5
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 1
    Just a note: the OP has to remind that the client side must keep track one what or another the previous offset and send the information to the server script, or else it won't change much the problem – Kaddath Nov 21 '18 at 13:19
1
  • You need to set a offset in hidden field.
  • On clicking load more, you need to get offset, calculate next batch and update offset in same hidden field
  • that new offset, should be passed to query.

your query looks like

SELECT ArticleTitle, PreviewText, PreviewImage 
FROM Articles 
ORDER BY ID DESC 
LIMIT 0, 4 

first time offset is 0

next time it will be 5 (if you are loading 5 records every time)

then next time it will be 10 and so on

Naveed Ramzan
  • 3,565
  • 3
  • 25
  • 30
  • can you please show me how to dynamically change the value of offset without this pagination thing...thanks – Tech guy Nov 22 '18 at 16:45
  • You can make an input field hidden and value is 5. show first 5 rows. a button clicked, get value of that hidden field and add 5 more, 1st iteration: 5 in field, so that 5 will be offset, new value of field will be 10 2nd iteration: 10 in field, so that 10 will be offset, new value of field will be 15 and so on – Naveed Ramzan Nov 22 '18 at 17:42
  • $offset = 0; can I use if(isset($_POST['Offset_Field_Request'])){ $offset = $offset + 4; } – Tech guy Nov 23 '18 at 17:12
  • Yup seems ok for this scenario – Naveed Ramzan Nov 26 '18 at 04:33
  • But as soon as I am sending new Ajax request the value of $offset and $Limit is same. ie; the variables are having same value and same records are being fetched. – Tech guy Nov 27 '18 at 07:01
  • that offset you need to add in ajax request. Like get current offset from hidden field and add 4 and pass to the request. also update new offset to hidden field. – Naveed Ramzan Dec 04 '18 at 07:29