Pagination keeps showing the same portion of SQL data

前端 未结 3 1861
长情又很酷
长情又很酷 2021-01-29 05:46

I have a really large data set from SQL that i need to paginate.

I have an issue with my pagination code. The code does show the page number in the URL

3条回答
  •  日久生厌
    2021-01-29 05:57

    You should change

    $sql='SELECT * FROM ETF';
    $result = mysqli_query($con, $sql);
    $number_of_results = mysqli_num_rows($result);
    

    to something like this

    $count = mysqli_fetch_assoc(mysqli_query($con,"SELECT COUNT(*) AS RC FROM ETF"));
    $number_of_results=$count['RC'];
    

    because it is faster to get count from mysql (index if its a large table) instead of fetching all table data (because SELECT *...) for looping trough it just for row counting.

    // retrieve selected results from database and display them on page
    $sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;
    

    You using good query, but using wrong function to get its results.

    Query should be

    $sql='SELECT * FROM ETF LIMIT ' . $results_per_page . "," .$this_page_first_result;
    

    or:

    $sql='SELECT * FROM ETF LIMIT ' . $results_per_page . " OFFSET " .$this_page_first_result;
    

    Both of these work.

    Change

    while($row = mysqli_fetch_array($result)) {
      echo $row['ETF'] . ' ' . $row['ETF NAME']. '
    '; }

    to

    while($row = mysqli_fetch_assoc($result)) {
      echo $row['ETF'] . ' ' . $row['ETF NAME']. '
    '; }

    because "mysqli_fetch_array" fetch array width numbered indexes (for example 0, 1, 2...) not a text ones you are trying to use, but "mysqli_fetch_assoc" does that you need.

    Full code should be

    ';
    }
    // display the links to the pages
    for($page=1;$page<=$number_of_pages;$page++)
    {
        echo''.$page.' ';
    }
    mysqli_close($con);
        ?>
    

提交回复
热议问题