Easy to use PHP function to create back- forward links for a result set


Share Database resultset navigation ver. 1.00

released: 2005-11-13
Use this small function to create page links for your (MySQL) database resultset. This PHP function is all you need to create forward / backward links (paging) for the records in a database resultset. The setup is very easy, just call the function at the place where the links to have appear. Then create a variable for the current limit inside your SQL and create a variable with the total number of records in your resultset. The function takes care about an existing query string and creates the whole html code you need for the page navigation.

Viewed 15852 times

Rating: script rated with stars
 

<?php
// example variable
$sql_limit = (isset($_GET['limit'])) ? $_GET['limit'] : 0;

function navigation_links($curr_limit, $num_records, $limit_val, $limit_var = "limit", $next = "next >", $prev = "< prev", $seperator = "|") {
    // rebuild query string
    if (!empty($_SERVER['QUERY_STRING'])) {
        $parts = explode("&", $_SERVER['QUERY_STRING']);
        $newParts = array();
        foreach ($parts as $val) {
            if (stristr($val, $limit_var) == false) array_push($newParts, $val);
        }
        $qs = (count($newParts) > 0) ? "&".implode("&", $newParts) : "";
    } else {
        $qs = "";
    }
    $navi = "";
    if ($curr_limit > 0) {
        $navi .= "<a href=\"".$_SERVER['PHP_SELF']."?".$limit_var. "=".($curr_limit-$limit_val).$qs."\">".$prev."</a>";
    }
    $navi .= " ".$seperator." ";
    if ($curr_limit < ($num_records-$limit_val)) {
        $navi .= "<a href=\"".$_SERVER['PHP_SELF']."?".$limit_var. "=".($curr_limit+$limit_val).$qs."\">".$next."</a>";
    }
    return trim($navi, " | ");
}

// example placing links ($num_all is the value of all records in you result set)
echo navigation_links($sql_limit, $num_all, 10);
?>