处理分页
如何做...
namespace Application\Database;
class Paginate
{
const DEFAULT_LIMIT = 20;
const DEFAULT_OFFSET = 0;
protected $sql;
protected $page;
protected $linesPerPage;
}如何运行...

参考
最后更新于
namespace Application\Database;
class Paginate
{
const DEFAULT_LIMIT = 20;
const DEFAULT_OFFSET = 0;
protected $sql;
protected $page;
protected $linesPerPage;
}
最后更新于
public function __construct($sql, $page, $linesPerPage)
{
$offset = $page * $linesPerPage;
switch (TRUE) {
case (stripos($sql, 'LIMIT') && strpos($sql, 'OFFSET')) :
// no action needed
break;
case (stripos($sql, 'LIMIT')) :
$sql .= ' LIMIT ' . self::DEFAULT_LIMIT;
break;
case (stripos($sql, 'OFFSET')) :
$sql .= ' OFFSET ' . self::DEFAULT_OFFSET;
break;
default :
$sql .= ' LIMIT ' . self::DEFAULT_LIMIT;
$sql .= ' OFFSET ' . self::DEFAULT_OFFSET;
break;
}
$this->sql = preg_replace('/LIMIT \d+.*OFFSET \d+/Ui',
'LIMIT ' . $linesPerPage . ' OFFSET ' . $offset,
$sql);
}use PDOException;
public function paginate(
Connection $connection,
$fetchMode,
$params = array())
{
try {
$stmt = $connection->pdo->prepare($this->sql);
if (!$stmt) return FALSE;
if ($params) {
$stmt->execute($params);
} else {
$stmt->execute();
}
while ($result = $stmt->fetch($fetchMode)) yield $result;
} catch (PDOException $e) {
error_log($e->getMessage());
return FALSE;
} catch (Throwable $e) {
error_log($e->getMessage());
return FALSE;
}
} if ($sql instanceof Finder) {
$sql->limit($linesPerPage);
$sql->offset($offset);
$this->sql = $sql::getSql();
} elseif (is_string($sql)) {
switch (TRUE) {
case (stripos($sql, 'LIMIT')
&& strpos($sql, 'OFFSET')) :
// 以上第3点所示的剩余代码
}
}public function getSql()
{
return $this->sql;
}<?php
define('DB_CONFIG_FILE', '/../config/db.config.php');
define('LINES_PER_PAGE', 10);
define('DEFAULT_BALANCE', 1000);
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');use Application\Database\ { Finder, Connection, Paginate};
$conn = new Connection(include __DIR__ . DB_CONFIG_FILE);
$sql = Finder::select('customer')->where('balance < :bal');$page = (int) ($_GET['page'] ?? 0);
$bal = (float) ($_GET['balance'] ?? DEFAULT_BALANCE);
$paginate = new Paginate($sql::getSql(), $page, LINES_PER_PAGE);
?><h3><?= $paginate->getSql(); ?></h3>
<hr>
<pre>
<?php
printf('%4s | %20s | %5s | %7s' . PHP_EOL,
'ID', 'NAME', 'LEVEL', 'BALANCE');
printf('%4s | %20s | %5s | %7s' . PHP_EOL,
'----', str_repeat('-', 20), '-----', '-------');
foreach ($paginate->paginate($conn, PDO::FETCH_ASSOC,
['bal' => $bal]) as $row) {
printf('%4d | %20s | %5s | %7.2f' . PHP_EOL,
$row['id'],$row['name'],$row['level'],$row['balance']);
}
printf('%4s | %20s | %5s | %7s' . PHP_EOL,
'----', str_repeat('-', 20), '-----', '-------');
?>
<a href="?page=<?= $page - 1; ?>&balance=<?= $bal ?>">
<< Prev </a>
<a href="?page=<?= $page + 1; ?>&balance=<?= $bal ?>">
Next >></a>
</pre>