Home > Article > Backend Development > PHP automatic paging function_PHP tutorial
php tutorial automatic paging function
If you don’t want to write sql code repeatedly, you can use the following function to automatically process it.
$__t_page_moyo_html = '';
/**
*
* Temporary code: paging processing function
* @param string $sql
*/
function page_moyo($sql = '')
{
global $__t_page_moyo_html;
if ($sql == '')
{
return $__t_page_moyo_html;
}
// config
$max = 12;
$flag = 'page';
// step .1 Process sql statement
$sql_count = preg_replace('/select.*?from/is', 'select count(*) as mcnt from', $sql);
// step .2 Get the amount of data
$result = dbc()->query($sql_count)->getrow();
$total = $result['mcnt'];
// step .3 Determine whether paging is needed
if ($total < $max)
{
return $sql;
}
// step .4 Get the current number of pages
$pn = isset($_get[$flag]) ? (int)$_get[$flag] : 1;
if ($pn <= 0) $pn = 1;
// step .5 Restructure sql Statement
$sql = $sql . ' limit '.($pn-1)*$max.','.$max;
// step .6 Assemble paging html code
$url = $ _server['request_uri'];
if (preg_match('/'.$flag.'=d+/i', $url))
{
$url = preg_replace('/[&]? '.$flag.'=d+/', '', $url);
}
$pageall = ceil($total/$max);
$pre = '';
if ($pn > 1)
{
$pre = ' / Previous page';
}
$nxt = ' / Next page';
$html = 'Homepage'.$pre. $nxt.' / Last page';
$__t_page_moyo_html = $ html;
Return $sql;
}
Use page_moyo to process the sql statement before performing sql query
$sql = page_moyo($sql);
Then directly call page_moyo output where you need to display the paging link
echo page_moyo();
If you want to perform two consecutive SQL queries with large data volume, you must store the current time after the first query paging code, otherwise the next sql query will overwrite it