SoFunction
Updated on 2025-03-10

PHP implementation of oracle pagination function example

This article describes the oracle pagination function implemented by PHP. Share it for your reference, as follows:

MySQL has limit. When paging, we can use limit 30, 40, while Oracle does not have limit. Use other methods to replace - rownum.

1. The underlying method

/**
  * Data connection
  */
function connect($db_user, $db_pwd, $db_name, $db_nls)
{
 $this->dbh = oci_connect($db_user, $db_pwd, $db_name, $db_nls);
}
function getall($query, $start=0, $rows=-1)
{
 $this->dbh = emptyempty($this->dbh) ? $this->connect() : $this->dbh;
 $this->sth = oci_parse($this->dbh, $query);
 oci_execute($this->sth, OCI_DEFAULT) or $this->error($this->sth, $query);
 oci_fetch_all($this->sth, $res, $start, $rows, OCI_FETCHSTATEMENT_BY_ROW+OCI_ASSOC);
 return $res;
}
/**
 * Get the number of pages
 *
 * $query string query statement
 * $total int Total number of entries
 * $page int Number of pages
 * $rows int Number of displays per page
 * @return integer Total row count
 */
function getpage($query, $total, $page, $rows=VAR_PAGENAV_ROWS)
{
 $start_row = ($page - 1) * $rows + 1;
 $start_row = $start_row > $total ? 1 : $start_row;
 $end_row  = $start_row + $rows - 1;
 $end_row  = $end_row > $total ? $total : $end_row;
 $query   = "SELECT * FROM ( SELECT ROWNUM as row_num, r.* FROM ( $query ) r WHERE ROWNUM <= $end_row ) WHERE $start_row <= row_num";
 return $this->getall($query);
}
/**
 * Get the total number of rows of a query
 *
 * $string $sql query statement
 *
 * return integer Total row count
 */
function getcount($sql){
 $subSQL = 'select count(*) '.stristr($sql, 'from');
 return $this->getone($subSQL);
}
function getone($query)
{
 $row = $this->getrow($query);
 if (is_array($row))
 $one = current($row);
 else
 $one = '';
 unset($row);
 return $one;
}
function getrow($query)
{
 if (false === stripos($query, 'COUNT(')) {
 if (false === stripos($query, 'WHERE')) {
 $query .= ' WHERE ROWNUM = 1';
 } else {
 $query .= ' AND ROWNUM = 1';
 }
 }
 $result = $this->getall($query, 0, 1);
 if (emptyempty($result))
 $row = array();
 else
 $row = $result[0];
 unset($result);
 return $row;
}

I'll write some comments on the two main methods

2. Calling methods

$total = $this->db->getcount($sql);
$result = $this->db->getpage($sql,$total,$page,$page_number);

The above is just a part of the code, which is also the most core.

For more information about PHP database operations, please visit the special topic of this site:Summary of common database operation techniques for php》、《Summary of PHP's skills to operate database based on pdo"and"PHP+mysql database operation tutorial》。

I hope this article will be helpful to everyone's PHP programming.