dasdfs fsafds
dasdfs fsafds

Reputation: 1

Page numbers not functioning

I'm currently trying to implement pagination into my table, however, whenever i click on the pages, they do not show me the next page even though the link on the address bar clearly says page=2, page=3 etc. Im wondering if theres any mistakes that i did with my code. Thank you

    $totalPerPage = 20;
    $size= "50";
    $sql = ("SELECT DISTINCT * FROM shoe s 
            INNER JOIN shoelace sc ON s.cod = sc.cod
            WHERE s.shoefit =?");

    $stmt = $db->prepare($sql);
    $stmt->execute([$size]);

    $numberofResults = $stmt->rowCount();
        $numberOfPages = ceil($numberofResults/$totalPerPage);

        if(isset($_GET['page'])){
            $page = $_GET['page'];
        }else{
            $page = 1;
        }

        $thePageFormula = ($page-1)*$totalPerPage;
        $query = ("SELECT DISTINCT * FROM shoe s 
                INNER JOIN w_shoelace sc ON s.cod = sc.cod
                WHERE s.shoefit =?
                LIMIT $thePageFormula,$totalPerPage");

        $stmt2 = $db->prepare($query);
        $stmt2->execute([$size]);


while($row = $stmt2->fetch(PDO::FETCH_ASSOC)){
    //echos infromation in table form
    echo "<table><tr onclick='javascript:showRow(this);'><td>" 
    . $row['shoename'] . "</td><td>"
    . utf8_encode($row['shoecolor']) . "</td><td>"
    <img src='data:image/jpeg;base64,".base64_encode($row['shoeimg'])."'width='50' height='30'/></td><tr>"; 
    echo "</table>";
} 



   for ($page=1; $page <= $numberOfPages ; $page++){ 

    echo "<div class='pagination'> 
            <a href='?page=" . $page . "'>" . $page . "</a>
        </div>";

} 

Upvotes: 0

Views: 53

Answers (1)

Ropali Munshi
Ropali Munshi

Reputation: 3006

I think the problem is in this SQL query

SELECT DISTINCT * FROM shoe s 
                INNER JOIN w_shoelace sc ON s.cod = sc.cod
                WHERE s.shoefit =?
                LIMIT $thePageFormula,$totalPerPage

For pagination you have to always maintain the offset value for the SQL query which means from where it should start fetching the data from database. The above query should look something like this

SELECT DISTINCT * FROM shoe s 
                    INNER JOIN w_shoelace sc ON s.cod = sc.cod
                    WHERE s.shoefit =?
                    LIMIT *limit_to_show_per_page*, *offset*

If you start fetching the data from database and your limit is 10 for first page then your offset value must be 0 and if go to second page then the limit per page would be fixed that is 10 and your offset would change from 0 to 10 and so on. Hope you get the point.

Upvotes: 1

Related Questions