简体   繁体   中英

PHP + MYSQL Pages - OOP and PDO

I'm quite new to OOP and PDO and have been unable to figure out how to show MYSQL results by pages (eg 10 per page). What would be the best way to do this?

    public function getResults() { 
    try {

        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

        $sql = "SELECT * FROM table ORDER BY id DESC LIMIT 10";
        $result = $con->query($sql);

        while($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $msg_id = $row['id'];
        echo '<div id="results">' .$msg_id. '</div>';
        }

      $con = null;   

     }catch(PDOException $e) {

     echo $e->getMessage();

     }

 }

}

This seems like a good start. To get the next set of results, you would need to use this statement:

SELECT * FROM table ORDER BY id DESC LIMIT 10, 10

This would return you the results 11 to 20.

More generally, you would like to have a GET parameter that enables you to show any set:

http://mywebsite.com/mypage.php?set=1

You would then construct your query dynamically based on the set number:

$sql = sprintf("SELECT * FROM table ORDER BY id DESC LIMIT %s, 10", $con->quote($_GET['set'] - 1)*10));

The part about quoting is very important as it protects you against SQL injection (you can google it up for more info).

Try to add additional parameters to the function getResults() and the additional parameters would be $start , $count , then use these variables in your query

public function getResults($start, $count) { 
    try {

        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $query = $con->prepare("SELECT * FROM table ORDER BY id DESC LIMIT :start, :count");
        $query->bindValue(':start', $start);
        $query->bindValue(':count', $count);
        $query->execute();

        while($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $msg_id = $row['id'];
            echo '<div id="results">' .$msg_id. '</div>';
        }

       $con = null;   

    } catch(PDOException $e) {
         echo $e->getMessage();
    }

}

This in my opinion, " for what it is worth", is the best pagination class i have come across. You can implement it with only four lines of codes. It will set up page links top and bottom and allow user to choose how many rows per page.

Pagination class link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM