Thursday, March 12, 2009

A simple Pagination function

Following function can be used for pagination blocks. You need to call this function, and print the return string. The return string format is << <> >>
i.e. first page link, previous page link, page numbers link, next page link, last page link.
You need to add javascript function called paginate(page_no) which takes page no as the argument & in turns do AJAX call for fetching the next records.
Argument list for pagination function:
  1. $current_page: current page number
  2. $cnt: total records
  3. $limit: No of records to be displayed

function pagination($current_page,$cnt,$limit){
$last_page = ceil($cnt/$limit);
$str = "";
$first_pg = "";
$prev_pg = "";
$next = "";
$last = "";

if($last_page == 1){
$first_pg = " << ";
$prev_pg = " < ";
}else{
if($current_page > 1){
$first_pg = "<a href=\"javascript:void(0)\" onClick=\"paginate(1)\"> << </a>";
$prev_pg = "
<a href=\"javascript:void(0)\" onClick=\"paginate($current_page-1)\"> < </a>";
}
for($i=1;$i<=$last_page;$i++){
if($i == $current_page)
$str .= $i." | ";
else
$str .= "<a href=\"javascript:void(0)\" onClick=\"paginate($i)\"><u>".$i."</u></a> | ";
}
$str = substr($str,0,strlen($str)-2);


if($current_page != $last_page){
$next = "<a href=\"javascript:void(0)\" onClick=\"paginate($current_page+1)\"> > </a>";
$last = "
<a href=\"javascript:void(0)\" onClick=\"paginate($last_page)\"> >> </a>";
}
if($current_page == $last_page){
$next = " > ";
$last = " >> ";
}

}
$page_string = $first_pg.$prev_pg.$str.$next.$last;
return $page_string;
}



Truncating the text

In many places the description or text needs to be truncated. Following function can be used to truncate the text in such a way that the words are not half chopped up.

Argument List:
  1. $mystring: The text
  2. $limit: length of the string upto which string is to be truncate.
  3. $pad: The string which shows continuation. Default it takes 3 dots (...) .


function truncate_text($mystring, $limit = 153,$pad ="..."){
if(strlen($mystring) < $limit)
return $mystring;
$rstring = substr($mystring,0,$limit);
$no_of_chars = strrpos($rstring," ");
if($no_of_chars < $limit)
$rstring = substr($mystring,0,$no_of_chars).$pad;
return $rstring;
}