PHP script paging

Asked

Viewed 522 times

7

I would like to know how I can make a PHP pagination (in this case, 10 items per page).

The exhibition is being made this way:

<?php foreach($pdo->query('SELECT * FROM videos ORDER BY id DESC') as $c): ?>
    <li>
        <p>
            <strong>
                <?php echo $c['title'];?>
            </strong>
        </p>
        <a title="<?php echo $c['title'] ?>" class="lightbox" href="http://www.youtube.com/embed/<?php echo $c['video_ed'] ?>?rel=0&amp;wmode=transparent">
            <img src="http://i1.ytimg.com/vi/<?php echo $c['video_ed'] ?>/default.jpg" alt="<?php echo $c['title']; ?>" />
        </a>

    </li>
<?php endforeach; ?>

I haven’t been able to find a method that works...

  • 5

    See the answer here : http://answall.com/questions/26303/como-fazer-pagina%C3%A7%C3%A3o-php-e-mysql

1 answer

8


Very simply:

$page = isset($_GET['page']) (int) $_GET['page'] : 1;

$limit = 10;

$offset = ($page * $limit) - $limit; 
// Gera 0,1,2,3, para cada página incrementada

$stmt = $pdo->prepare("SELECT * FROM minha_tabela LIMIT $offset,$limit"); 

$stmt->execute(); 

$resultados = $stmt->fetchAll();

$stmt = $pdo->prepare('SELECT count(*) as count 
FROM minha_Tabela'); 

$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);

$total_de_paginas = $row['count'];

In HTML to generate links, you do so:

<?php for($i = 1; $i <= $total_de_paginas; $i++): ?>
    <a href="?<?php echo http_build_query(array('page' => $i)) ?>">
      <?php echo $i ?>
   </a>

<?php endfor ?>

If you run the foreach on your $resultados, the results of the paged consultation will come.

  • 2

    Simple and goal +1, from to use placeholders in the limit/off set if you want.

  • Very good! I appreciate the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.