How to paginate in PHP with MVC?

1

I have a controller and a view that work perfectly, I found it on the internet but now I would like to paginate the records and I can not do it with MVC:

Driver

class Home

{

public function saludo($nombre)    {

    View::set("name", $nombre);

    View::set("title", "Custom MVC");

    View::render("home");

}



public function users()

{

    $users = UserAdmin::getAll();

    View::set("users", $users);

    View::set("title", "Custom MVC");

    View::render("users");

}

}

Vista

<tbody>

            <?php

            foreach ($users as $user)

            {

            ?>

            <tr>

                <td><?php echo $user["id"] ?></td>

                <td><?php echo $user["nombre"] ?></td>

            </tr>

            <?php

            }

            ?>

        </tbody>

This is the model

class User
{

public static function getAll()
{

    try {

     $connection = Database::instance();

     $sql = "SELECT * from usuarios";

     $query = $connection->prepare($sql);

     $query->execute();

     return $query->fetchAll();

    }
    catch(\PDOException $e)

    {
     print "Error!: " . $e->getMessage();

 }
    
asked by Fercho Jerez 09.08.2016 в 04:05
source

1 answer

1

First, you must obtain the page you are on using url parameters and, based on this, the users pages. For example:

in the controller, you must recover the pagination variables ( page and qty , if you want both):

public function users() {
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $qty = 10; // o $_GET['qty'] si quieres que sea parametrizable

    $users = UserAdmin::getAll($page, $qty);

    View::set("users", $users);

    View::set("title", "Custom MVC");

    View::render("users");
}

Then in your model, you should limit your results to the desired amount, with an offset of cantidad * (pagina - 1) :

public static function getAll($page = 1, $qty = 10){
  try {
    $connection = Database::instance();

    $sql = "SELECT * from usuarios LIMIT ? OFFSET ?";

    if($page <= 0) $page = 1;  

    $query = $connection->prepare($sql, array($qty, $qty * ($page-1)));

    $query->execute();

    return $query->fetchAll();

  } catch(\PDOException $e) {
    print "Error!: " . $e->getMessage();
  }
}
    
answered by 09.08.2016 в 11:49