Pagination script PHP [duplicate]

7

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

The display 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/<?phpecho$c['video_ed']?>/default.jpg" alt="<?php echo $c['title']; ?>" />
        </a>

    </li>
<?php endforeach; ?>

I have not yet been able to find a method that works ...

    
asked by anonymous 27.10.2015 / 15:49

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 foreach on your $resultados , the results of the paged query will come.

    
27.10.2015 / 16:08