当前位置: 首页 > 编程文章 >

基于PHP的高效MongoDB分页类实现(避免Skip性能陷阱)

基于PHP的高效MongoDB分页类实现(避免Skip性能陷阱)

作者:顾辰时间:2025-07-02 10:00:12浏览:760

传统MongoDB使用skip+limit进行分页时,随着页面越靠后效率越低。本方案通过记录每页最后一条记录的ID作为下一页查询条件,每次仅查询固定数量的页面大小记录,从而保持稳定的查询效率。文章提供了完整的PHP操作类mongodb.class.php和分页逻辑类page.class.php的实现代码及测试用例。

本文目录收起

MongoDB高效分页原理与实现

在MongoDB中采用skip结合limit的方式进行分页存在明显缺陷:系统需先检索出全部匹配结果再执行跳过操作,导致查询深度增加时性能急剧下降。

优化的策略是利用查询条件获取当前页的最后一条记录,将其作为下一页的起始查询依据。这种方式确保每次请求仅返回指定大小的数据量,维持高效的查询性能。

具体实现涉及三个核心文件:mongodb.class.php用于底层数据库操作,page.class.php处理分页逻辑,test.php提供测试验证。

mongodb.class.php是MongoDB的基础操作封装类。

//MongoDB操作类 class DB {

private $CI; private $config_file = 'MongoDB';

private $connection; private $db; private $connection_string; private $collection = ''; private $host; private $port; private $user; private $pass; private $dbname; private $key; private $persist; private $persist_key;

private $selects = array(); private $wheres = array(); private $sorts = array(); private $page_sorts = array();

private $limit = 999999; private $offset = 0;

/** * -------------------------------------------------------------------------------- * CONSTRUCTOR * -------------------------------------------------------------------------------- * * Automatically check if the Mongo PECL extension has been installed/enabled. * Generate the connection string and establish a connection to the MongoDB. */

public function __construct($MONGODB_CONFIG) { if(!class_exists('Mongo')) { show_error("The MongoDB PECL extension has not been installed or enabled", 500); } /** $config['mongo_host'] = '221.234.43.144'; $config['mongo_port'] = 27017; $config['mongo_db'] = 'test'; $config['mongo_user'] = ''; $config['mongo_pass'] = ''; $config['mongo_persist'] = TRUE; * */ $this->connection_string($MONGODB_CONFIG); $this->connect(); }

/** * -------------------------------------------------------------------------------- * Switch_db * -------------------------------------------------------------------------------- * * Switch from default database to a different db */

public function switch_db($database = '') { if(empty($database)) { show_error("To switch MongoDB databases, a new database name must be specified", 500); } $this->dbname = $database; try { $this->db = $this->connection->{$this->dbname}; return(TRUE); } catch(Exception $e) { show_error("Unable to switch Mongo Databases: {$e->getMessage()}", 500); } }

/** * -------------------------------------------------------------------------------- * SELECT FIELDS * -------------------------------------------------------------------------------- * * Determine which fields to include OR which to exclude during the query process. * Currently, including and excluding at the same time is not available, so the * $includes array will take precedence over the $excludes array. If you want to * only choose fields to exclude, leave $includes an empty array(). * * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar'); */

public function select($includes = array(), $excludes = array()) { if(!is_array($includes)) { $includes = array(); }

if(!is_array($excludes)) { $excludes = array(); }

if(!empty($includes)) { foreach($includes as $col) { $this->selects[$col] = 1; } } else { foreach($excludes as $col) { $this->selects[$col] = 0; } } return($this); }

/** * -------------------------------------------------------------------------------- * WHERE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents based on these search parameters. The $wheres array should * be an associative array with the field as the key and the value as the search * criteria. * * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar'); */

public function where($wheres = array()) { foreach($wheres as $wh => $val) { $this->wheres[$wh] = $val; } return($this); }

/** * -------------------------------------------------------------------------------- * WHERE_IN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is in a given $in array(). * * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */

public function where_in($field = "", $in = array()) { $this->where_init($field); $this->wheres[$field]['$in'] = $in; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE_NOT_IN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is not in a given $in array(). * * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */

public function where_not_in($field = "", $in = array()) { $this->where_init($field); $this->wheres[$field]['$nin'] = $in; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE GREATER THAN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is greater than $x * * @usage = $this->mongo_db->where_gt('foo', 20); */

public function where_gt($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$gt'] = $x; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE GREATER THAN OR EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is greater than or equal to $x * * @usage = $this->mongo_db->where_gte('foo', 20); */

public function where_gte($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$gte'] = $x; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE LESS THAN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is less than $x * * @usage = $this->mongo_db->where_lt('foo', 20); */

public function where_lt($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$lt'] = $x; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE LESS THAN OR EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is less than or equal to $x * * @usage = $this->mongo_db->where_lte('foo', 20); */

public function where_lte($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$lte'] = $x; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE BETWEEN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is between $x and $y * * @usage = $this->mongo_db->where_between('foo', 20, 30); */

public function where_between($field = "", $x, $y) { $this->where_init($field); $this->wheres[$field]['$gte'] = $x; $this->wheres[$field]['$lte'] = $y; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE BETWEEN AND NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is between but not equal to $x and $y * * @usage = $this->mongo_db->where_between_ne('foo', 20, 30); */

public function where_between_ne($field = "", $x, $y) { $this->where_init($field); $this->wheres[$field]['$gt'] = $x; $this->wheres[$field]['$lt'] = $y; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is not equal to $x * * @usage = $this->mongo_db->where_between('foo', 20, 30); */

public function where_ne($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$ne'] = $x; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE OR * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is in one or more values * * @usage = $this->mongo_db->where_or('foo', array( 'foo', 'bar', 'blegh' ); */

public function where_or($field = "", $values) { $this->where_init($field); $this->wheres[$field]['$or'] = $values; return($this); }

/** * -------------------------------------------------------------------------------- * WHERE AND * -------------------------------------------------------------------------------- * * Get the documents where the elements match the specified values * * @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' ); */

public function where_and( $elements_values = array() ) { foreach ( $elements_values as $element => $val ) { $this->wheres[$element] = $val; } return($this); }

/** * -------------------------------------------------------------------------------- * WHERE MOD * -------------------------------------------------------------------------------- * * Get the documents where $field % $mod = $result * * @usage = $this->mongo_db->where_mod( 'foo', 10, 1 ); */

public function where_mod( $field, $num, $result ) { $this->where_init($field); $this->wheres[$field]['$mod'] = array ( $num, $result ); return($this); }

/** * -------------------------------------------------------------------------------- * Where size * -------------------------------------------------------------------------------- * * Get the documents where the size of a field is in a given $size int * * @usage : $this->mongo_db->where_size('foo', 1)->get('foobar'); */

public function where_size($field = "", $size = "") { $this->_where_init($field); $this->wheres[$field]['$size'] = $size; return ($this); }

/** * -------------------------------------------------------------------------------- * LIKE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the (string) value of a $field is like a value. The defaults * allow for a case-insensitive search. * * @param $flags * Allows for the typical regular expression flags: * i = case insensitive * m = multiline * x = can contain comments * l = locale * s = dotall, "." matches everything, including newlines * u = match unicode * * @param $enable_start_wildcard * If set to anything other than TRUE, a starting line character "^" will be prepended * to the search value, representing only searching for a value at the start of * a new line. * * @param $enable_end_wildcard * If set to anything other than TRUE, an ending line character "$" will be appended * to the search value, representing only searching for a value at the end of * a line. * * @usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE); */

public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) { $field = (string) trim($field); $this->where_init($field); $value = (string) trim($value); $value = quotemeta($value);

if($enable_start_wildcard !== TRUE) { $value = "^" . $value; }

if($enable_end_wildcard !== TRUE) { $value .= "$"; }

$regex = "/$value/$flags"; $this->wheres[$field] = new MongoRegex($regex); return($this); }

/** * -------------------------------------------------------------------------------- * ORDER BY PARAMETERS * -------------------------------------------------------------------------------- * * Sort the documents based on the parameters passed. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage = $this->mongo_db->where_between('foo', 20, 30); */

public function order_by($fields = array()) { foreach($fields as $col => $val) { if($val == -1 || $val === FALSE || strtolower($val) == 'desc') { $this->sorts[$col] = -1; } else { $this->sorts[$col] = 1; } } return($this); }

/** * -------------------------------------------------------------------------------- * LIMIT DOCUMENTS * -------------------------------------------------------------------------------- * * Limit the result set to $x number of documents * * @usage = $this->mongo_db->limit($x); */

public function limit($x = 99999) { if($x !== NULL && is_numeric($x) && $x >= 1) { $this->limit = (int) $x; } return($this); }

/** * -------------------------------------------------------------------------------- * OFFSET DOCUMENTS * -------------------------------------------------------------------------------- * * Offset the result set to skip $x number of documents * * @usage = $this->mongo_db->offset($x); */

public function offset($x = 0) { if($x !== NULL && is_numeric($x) && $x >= 1) { $this->offset = (int) $x; } return($this); }

/** * -------------------------------------------------------------------------------- * GET_WHERE * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage = $this->mongo_db->get_where('foo', array('bar' => 'something')); */

public function get_where($collection = "", $where = array(), $limit = 99999) { return($this->where($where)->limit($limit)->get($collection)); }

/** * -------------------------------------------------------------------------------- * GET * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage = $this->mongo_db->get('foo', array('bar' => 'something')); */

public function get($collection = "") { if(empty($collection)) { show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500); } $results = array(); $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);

$returns = array();

foreach($documents as $doc): $returns[] = $doc; endforeach; $this->clear(); return($returns);

  }

/** * -------------------------------------------------------------------------------- * COUNT * -------------------------------------------------------------------------------- * * Count the documents based upon the passed parameters * * @usage = $this->mongo_db->get('foo'); */

public function count($collection = "") { if(empty($collection)) { show_error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500); } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)->skip((int) $this->offset)->count(); $this->clear(); return($count); } /** * 自增ID实现 * return insert_id */ private function insert_inc($table) { $update = array('$inc'=>array('id'=>1)); $query = array('table'=>$table); $command = array( 'findandmodify'=>'_increase', 'update'=>$update, 'query'=>$query, 'new'=>true, 'upsert'=>true ); $id = $this->db->command($command); return $id['value']['id']; } /** * -------------------------------------------------------------------------------- * INSERT * -------------------------------------------------------------------------------- * * Insert a new document into the passed collection * * @usage = $this->mongo_db->insert('foo', $data = array()); */

public function insert($collection = "", $data = array()) { if(empty($collection)) { show_error("No Mongo collection selected to insert into", 500); }

if(count($data) == 0 || !is_array($data)) { show_error("Nothing to insert into Mongo collection or insert is not an array", 500); }

try { $inc = $this->insert_inc($collection); $data['_id'] = $inc; $result = $this->db->{$collection}->insert($data, array('fsync' => TRUE)); if($result['ok'] || $result){ return true; } else{ return false; } } catch(MongoCursorException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); }

  }

/** * -------------------------------------------------------------------------------- * UPDATE * -------------------------------------------------------------------------------- * * Update a document into the passed collection * * @usage = $this->mongo_db->update('foo', $data = array()); */

public function update($collection = "", $data = array(), $flage = false) { if(empty($collection)) { show_error("No Mongo collection selected to update", 500); } if(count($data) == 0 || !is_array($data)) { show_error("Nothing to update in Mongo collection or update is not an array", 500); } unset($data['_id']); if($flage){ $arr = $this->wheres; unset($arr['_id']); if(is_array($arr)){ foreach($arr as $key => $w){ unset($data[$key]); } } } try { $res = $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => TRUE, 'multiple' => FALSE)); $this->clear(); return $res; } catch(MongoCursorException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); }

  }

/** * -------------------------------------------------------------------------------- * UPDATE_ALL * -------------------------------------------------------------------------------- * * Insert a new document into the passed collection * * @usage = $this->mongo_db->update_all('foo', $data = array()); */

public function update_all($collection = "", $data = array()) { if(empty($collection)) { show_error("No Mongo collection selected to update", 500); }

if(count($data) == 0 || !is_array($data)) { show_error("Nothing to update in Mongo collection or update is not an array", 500); }

try { $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => TRUE, 'multiple' => TRUE)); $this->clear(); return(TRUE); } catch(MongoCursorException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); }

  }

/** * -------------------------------------------------------------------------------- * DELETE * -------------------------------------------------------------------------------- * * delete document from the passed collection based upon certain criteria * * @usage = $this->mongo_db->delete('foo', $data = array()); */

public function delete($collection, $where) { if(empty($collection)) { show_error("No Mongo collection selected to delete from", 500); } if(!$where){ show_error("No data input to delete", 500); } try { $this->wheres = $where; $this->db->{$collection}->remove($this->wheres); $this->clear(); return(TRUE); } catch(MongoCursorException $e) { show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); }

  }

/** * -------------------------------------------------------------------------------- * DELETE_ALL * -------------------------------------------------------------------------------- * * Delete all documents from the passed collection based upon certain criteria * * @usage = $this->mongo_db->delete_all('foo', $data = array()); */

public function delete_all($collection = "") { if(empty($collection)) { show_error("No Mongo collection selected to delete from", 500); }

try { $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => FALSE)); $this->clear(); return(TRUE); } catch(MongoCursorException $e) { show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); }

  }

/** * -------------------------------------------------------------------------------- * ADD_INDEX * -------------------------------------------------------------------------------- * * Ensure an index of the keys in a collection with optional parameters. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage = $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE)); */

public function add_index($collection = "", $keys = array(), $options = array()) { if(empty($collection)) { show_error("No Mongo collection specified to add index to", 500); }

if(empty($keys) || !is_array($keys)) { show_error("Index could not be created to MongoDB Collection because no keys were specified", 500); } foreach($keys as $col => $val) { if($val == -1 || $val === FALSE || strtolower($val) == 'desc') { $keys[$col] = -1; } else { $keys[$col] = 1; } }

if($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) { $this->clear(); return($this); } else { show_error("An error occured when trying to add an index to MongoDB Collection", 500); } }

/** * -------------------------------------------------------------------------------- * REMOVE_INDEX * -------------------------------------------------------------------------------- * * Remove an index of the keys in a collection. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1)); */

public function remove_index($collection = "", $keys = array()) { if(empty($collection)) { show_error("No Mongo collection specified to remove index from", 500); }

if(empty($keys) || !is_array($keys)) { show_error("Index could not be removed from MongoDB Collection because no keys were specified", 500); }

if($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) { $this->clear(); return($this); } else { show_error("An error occured when trying to remove an index from MongoDB Collection", 500); } }

/** * -------------------------------------------------------------------------------- * REMOVE_ALL_INDEXES * -------------------------------------------------------------------------------- * * Remove all indexes from a collection. * * @usage = $this->mongo_db->remove_all_index($collection); */

public function remove_all_indexes($collection = "") { if(empty($collection)) { show_error("No Mongo collection specified to remove all indexes from", 500); }

$this->db->{$collection}->deleteIndexes(); $this->clear(); return($this); }

/** * -------------------------------------------------------------------------------- * LIST_INDEXES * -------------------------------------------------------------------------------- * * Lists all indexes in a collection. * * @usage = $this->mongo_db->list_indexes($collection); */ public function list_indexes($collection = "") { if(empty($collection)) { show_error("No Mongo collection specified to remove all indexes from", 500); } return($this->db->{$collection}->getIndexInfo()); }

/** * -------------------------------------------------------------------------------- * DROP COLLECTION * -------------------------------------------------------------------------------- * * Removes the specified collection from the database. Be careful because this * can have some very large issues in production! */

public function drop_collection($collection = "") { if(empty($collection)) { show_error("No Mongo collection specified to drop from database", 500); } $this->db->{$collection}->drop(); return TRUE; }

/** * -------------------------------------------------------------------------------- * CONNECT TO MONGODB * -------------------------------------------------------------------------------- * * Establish a connection to MongoDB using the connection string generated in * the connection_string() method. If 'mongo_persist_key' was set to true in the * config file, establish a persistent connection. We allow for only the 'persist' * option to be set because we want to establish a connection immediately. */

private function connect() { $options = array(); if($this->persist === TRUE) { $options['persist'] = isset($this->persist_key) && !empty($this->persist_key) ? $this->persist_key : 'ci_mongo_persist'; }

try { $this->connection = new Mongo($this->connection_string, $options); $this->db = $this->connection->{$this->dbname}; return($this); } catch(MongoConnectionException $e) { show_error("Unable to connect to MongoDB: {$e->getMessage()}", 500); } }

/** * -------------------------------------------------------------------------------- * BUILD CONNECTION STRING * -------------------------------------------------------------------------------- * * Build the connection string from the config file. */

private function connection_string($MONGODB_CONFIG) {

$this->host = trim($MONGODB_CONFIG['HOST']); $this->port = trim($MONGODB_CONFIG['PORT']); $this->user = trim($MONGODB_CONFIG['USER']); $this->pass = trim($MONGODB_CONFIG['PWD']); $this->dbname = trim($MONGODB_CONFIG['DATABASE']); $this->persist = trim($MONGODB_CONFIG['PERSIST']); $this->persist_key = trim($MONGODB_CONFIG['PERSIST_KEY']);

$connection_string = "mongodb://";

if(empty($this->host)) { show_error("The Host must be set to connect to MongoDB", 500); }

if(empty($this->dbname)) { show_error("The Database must be set to connect to MongoDB", 500); }

if(!empty($this->user) && !empty($this->pass)) { $connection_string .= "{$this->user}:{$this->pass}@"; }

if(isset($this->port) && !empty($this->port)) { $connection_string .= "{$this->host}:{$this->port}/{$this->dbname}"; } else { $connection_string .= "{$this->host}"; }

$this->connection_string = trim($connection_string); }

/** * -------------------------------------------------------------------------------- * CLEAR * -------------------------------------------------------------------------------- * * Resets the class variables to default settings */

private function clear() { $this->selects = array(); $this->wheres = array(); $this->limit = NULL; $this->offset = NULL; $this->sorts = array(); }

/** * -------------------------------------------------------------------------------- * WHERE INITIALIZER * -------------------------------------------------------------------------------- * * Prepares parameters for insertion in $wheres array(). */

private function where_init($param) { if(!isset($this->wheres[$param])) { $this->wheres[$param] = array(); } } /** * -------------------------------------------------------------------------------- * 设置表 * -------------------------------------------------------------------------------- * 参数: * $table 表名 */ public function set_table($table){ $this->collection = $table; } /** * -------------------------------------------------------------------------------- * 获取表名 * -------------------------------------------------------------------------------- */ public function get_table(){ return $this->collection; } /** * -------------------------------------------------------------------------------- * 设置表排序 * -------------------------------------------------------------------------------- * 参数: * $orderby 排序 */ public function set_orderby($orderby){ $this->page_sorts = $orderby; } /** * -------------------------------------------------------------------------------- * 获取左边结果集 * -------------------------------------------------------------------------------- * 参数: * $left 左边显示的个数 * $last 定位当前页的值 * $size 页面大小 */ public function get_left($left, $last, $size = PAGE_SIZE){ if($last){ $order = $this->nor_orderby(); if($this->page_sorts[$this->key] == -1){ $this->where_gt($this->key, $last); } else { $this->where_lt($this->key, $last); } return $this->limit($left * $size)->order_by($order)->get($this->collection); } } /** * -------------------------------------------------------------------------------- * 获取右边结果集 * -------------------------------------------------------------------------------- * 参数: * $right 右边显示的个数 * $last 定位当前页的值 * $size 页面大小 */ public function get_right($right, $last, $size = PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key] == -1){ $this->where_lte($this->key, $last); } else { $this->where_gte($this->key, $last); } } return $this->limit($right * $size + 1)->order_by($this->page_sorts)->get($this->collection); } /** * -------------------------------------------------------------------------------- * 设置key * -------------------------------------------------------------------------------- * 参数: * $key 设置索引主键 */ public function set_key($key){ $this->key = $key; } /** * -------------------------------------------------------------------------------- * 求反 * -------------------------------------------------------------------------------- */ private function nor_orderby(){ foreach($this->page_sorts as $key => $order){ if($order == -1){ $orderby[$key] = 1; }else{ $orderby[$key] = -1; } } return $orderby; } /** * -------------------------------------------------------------------------------- * 获取上一页的值 * -------------------------------------------------------------------------------- * 参数: * $last 定位当前页的值 * $size 页面大小 */ public function get_prev($last, $size = PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key] == 1){ $this->where_lt($this->key,$last)->order_by(array($this->key => -1)); } else { $this->where_gt($this->key,$last)->order_by(array($this->key => 1)); } $result = $this->limit($size)->get($this->collection); } return $result[$size - 1][$this->key]; } /** * -------------------------------------------------------------------------------- * 获取下一页的值 * -------------------------------------------------------------------------------- * 参数: * $last 定位当前页的值 * $size 页面大小 */ public function get_next($last, $size = PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key] == 1){ $this->where_gte($this->key,$last); } else { $this->where_lte($this->key,$last); } } $result = $this->limit($size+1)->order_by($this->page_sorts)->get($this->collection); return $result[$size][$this->key]; } /** * -------------------------------------------------------------------------------- * 获取最后一页的值 * -------------------------------------------------------------------------------- * 参数: * $size 页面大小 */ public function get_last($size = PAGE_SIZE){ $res = $this->count($this->collection) % $size; $order = $this->nor_orderby(); if($res > 0){ $result = $this->limit($res)->order_by($order)->get($this->collection); return $result[$res - 1][$this->key]; }else{ $result = $this->limit($size)->order_by($order)->get($this->collection); return $result[$size - 1][$this->key]; } } /** * -------------------------------------------------------------------------------- * 分页查询 * -------------------------------------------------------------------------------- * 参数: * $last 定位当前页的值 * $size 页面大小 */ public function page_query($last, $size = PAGE_SIZE){ if($last){ if($this->page_sorts[$this->key]==1){ $this->where_gte($this->key,$last); } else { $this->where_lte($this->key,$last); } } return $this->limit($size)->order_by($this->page_sorts)->get($this->collection); } /** * 批量执行代码_插入 * @param String $collection * @param 二维数组 $code */ public function execute_insert($collection,$code){ //将二维数组分成js格式 $strcode=''; foreach($code as $k=>$v){ foreach($v as $kk=>$vv){ $strcode.='db.getCollection("'.$collection.'").insert({ "'.$kk.'":"'.$vv.'" });'; } } // retrun array([ok]=>1); return $this->db->execute($code); }

} ?> page.class.php mongodb分页逻辑类 复制代码 代码如下:

$ii = $this->left; $iii = 0; //显示左边的 for($i = $start; $i < $end; $i++, $ii--, $iii++){ if($this->page == $i){ $this->link.=''.$i.''; }else{ $the_id = $ii * $this->size - 1; if($the_id > 0){ $this->link.=''.$i.''; }else{ $the_id = ($iii - $this->left) * $this->size; $this->link.=''.$i.''; } } } }

//获取下一页 private function get_next(){ if($this->next){ $this->link.='下一页'; } } //获取尾页 private function get_last(){ if($this->page != $this->total){ $this->link.='尾页'; } } //跳转到 private function get_turnto(){ $this->turnto = ' 转到第 页'; } //求反 public function nor_orderby(){ foreach($this->orderby as $key => $order){ if($order==-1){ $orderby[$key] = 1; }else{ $orderby[$key] = -1; } } return $orderby; } //设置key public function set_key($key){ $this->key = $key; } //分页操作 public function show(){ $this->set_key($this->key); $this->set_orderby($this->orderby); $left = $this->get_left(); $right = $this->get_right(); $leftresult = $this->db->get_left($left, $this->last); $rightresult = $this->db->get_right($right, $this->last); $this->set_left_result($leftresult); $this->set_right_result($rightresult); $last = $this->db->get_last(); $this->set_last($last); return $this->get_link(); } } /* 调用例子rockmongo global $DB; $lastid = GET::UINT('id'); $table = 'log'; $key = '_id'; $orderby = array($key => -1); $DB->set_table($table); $DB->set_key($key); $DB->set_orderby($orderby); $log = $DB->page_query($lastid);

$page = new Page($lastid, $key, $orderby); $pager = $page->show(); */

?> test.php 测试代码 复制代码 代码如下:

$DB = new DB($config);

$table = 'whois'; //mongodb collection名 $key = '_id'; $orderby = array($key => -1);

$DB->set_table($table); $DB->set_key($key); $DB->set_orderby($orderby);

$log = $DB->page_query($lastid,5);

$page = new Page($lastid, $key, $orderby);

echo $pager = $page->show();


?>

上一篇
PHP实用分页类代码分享

本文分享两款实用的PHP分页类代码,包含样式展示与使用说明。这些分页组件结构清晰、易于集成,适合用于各类PHP项目的数据列表展示,帮助开发者快速实现高效的分页功能。

下一篇
Destoon数据库表结构详解与功能说明

本文汇总了Destoon系统中核心数据库表的名称及其对应的业务功能注释,旨在为二次开发人员提供快速查询支持。内容涵盖从基础的系统设置、会员管理到具体的业务模块如供应、求购、资讯、招聘等的数据存储结构,帮助开发者理解各表在平台运行中的具体作用。

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,016
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,004
Apache开启.htaccess及使用方法详解

本文介绍如何在本地Apache环境中启用.htaccess文件,主要涉及修改httpd.conf中的AllowOverride参数。同时详细解析.htaccess的多种实用功能,包括自定义错误页面、目录密码保护、IP访问限制、URL自动转向、默认首页设置以及防止图片盗链等配置方法,并分析了使用.htaccess对服务器性能和安全性的潜在影响。

2026.05.09 1,001
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,001
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,000
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,000

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。