Load more return duplicate

时间:2018-03-25 18:51:52

标签: javascript php jquery mysql

I trying to make load more content from database via php and ajax and read some tutorial but what I tried return duplicate entry. (here is just an example of my real code:)

Query:

$sql = "SELECT name FROM table WHERE cat = 2 LIMIT 10";

This load first 10 items.

Query for load more:

$limit = $_GET['limit'];
$current = $_GET['current'];

$sql = "SELECT name FROM table WHERE cat = 2 LIMIT $current OFFSET $limit";

Ajax:

$('.getMore').click(function() {
  var adslen = $('.Ads').length; // this return current items
  var limit = $(this).attr('data-limit'); // this return current item and items after load more

  $.ajax({
    type: "GET",
    data: {
      limit: limit,
      current: adslen
    },
    dataType: 'html',
    url: '/api/fetch.php?getBrowse',
    success: function(data) {
      // do something
    }
  });

});

For example now we have 10 items, after click on loadMore it load another 10 items, but the problem is it load duplicate itemes too, what I have done wrong?

HTML:

<a class="getMore" id="browse-getMore" data-limit="10">More</a>

After press load more it update data-limit:

<a class="getMore" id="browse-getMore" data-limit="20">More</a>

1 个答案:

答案 0 :(得分:0)

The problem is that you do not specify order. In your case SELECT statement returns rows with no specific order. When you run it once, it may return one list of records, when you run it twice (the same select query) it may return another set of records. So, do it like so:

$sql = "SELECT name FROM table WHERE cat = 2 ORDER BY id LIMIT $current OFFSET $limit";

And read theory. It says that relation (or table) is an unordered set of records, unless you specify order explicitly. And by the way, if you specify order, it is no longer a relation, if I'm not mistaken.