Skip to content

Instantly share code, notes, and snippets.

@umutakturk
Created September 29, 2012 19:01
Show Gist options
  • Save umutakturk/3804918 to your computer and use it in GitHub Desktop.
Save umutakturk/3804918 to your computer and use it in GitHub Desktop.
PHP MongoDB Simple Pagination
<?php
$mongodb = new Mongo("mongodb://username:password@localhost/database_name");
$database = $mongodb->database_name;
$collection = $database->collection;
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = 12;
$skip = ($page - 1) * $limit;
$next = ($page + 1);
$prev = ($page - 1);
$sort = array('createdAt' => -1);
$cursor = $collection->find()->skip($skip)->limit($limit)->sort($sort);
foreach ($cursor as $r) {
echo sprintf('<p>Added on %s. Last viewed on %s. Viewed %d times. </p>', $r['createdAt'], $r['lastViewed'], $r['counter']);
}
if($page > 1){
echo '<a href="?page=' . $prev . '">Previous</a>';
if($page * $limit < $total) {
echo ' <a href="?page=' . $next . '">Next</a>';
}
} else {
if($page * $limit < $total) {
echo ' <a href="?page=' . $next . '">Next</a>';
}
}
$mongodb->close();
?>
@usmanghani599
Copy link

You have missed $total.

$total= $cursor->count(); on line 17

@Paragsingh
Copy link

Hi
(MongoDB with PHP)Login script is not working. Plz Help

login; if(isset($_REQUEST['Login'])) { $username = $_REQUEST['username']; $password = $_REQUEST['password']; if($username!='' && $password!='') { $user = $collection->find( array('username' => $username,'password' => $password)); $num = $user->count(); if ($num > 0) { $_SESSION['userid'] = $user['_id']; header('Location: index.php'); } else { echo 'error'; } } else { echo "Fields are blank."; } } ?>

@masudewucse
Copy link

As my results is more then 89000 .. the $total= $cursor->count(); it tooks long long time to calculate.
Is it possible to do the pagination without counting the $total= $cursor->count(); ?
Answer would be appreciated. thanks

Copy link

ghost commented Jul 11, 2015

[...].ensureIndex({createdAt:1})

find($range,array('createdAt' => 1))->count();
or
find($range,array('_id' => 1))->count();

ref: http://edgystuff.tumblr.com/post/47080433433/counting-in-mongodb-just-got-much-faster
http://stackoverflow.com/questions/7658228/mongodb-count-is-very-slow-how-do-we-refine-work-around-with-it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment