Home » Pagination in PHP Function With Search Filter Example
Php

Pagination in PHP Function With Search Filter Example

Hello Friends, Are you looking for pagination in PHP with the search function? This is the right place for you. In this tutorial, we will discuss Php pagination function with search result option. All the developers require pagination in their projects.

Usually, developers fix the pagination in the listing of the pages. Its very time consuming and complicated work. So, we are introducing this article for PHP search and pagination function. This function is very easy to use and user-friendly.

We have divided this function into eight parts for better understanding:

  1. Mysql Database
  2. Database Connection
  3. Php Function
  4. PHP code
  5. Html code
  6. Call Function
  7. Full Project Code
  8. Conclusion

Let’s start…

Pagination in PHP Function with Search Filter

Pagination in PHP

View Demo

1) Mysql Database

First of all, we need to create one database in phpmyadmin and name it “test”.
Then create two dummy fields in the “test” database.

1) ID (INT 11)
2) Name (VARCHAR 255)

Now insert some dummy entries in that database so we can fetch those values. The database will be available in downloaded zip. You can change the database name and field name whatever you want. For now, we have to take the demo names.


CREATE TABLE `test` (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(255) NOT NULL
)
	

Also, you can paste the above all code in phpmyadmin and table will be automatically created.

2) Database Connection

Now we need to connect the database with our PHP project. Why do we need to connect the database? The answer is you can’t fetch the data from the database without a connection.
How to fix database connection? Follow the below code snippet:


ini_set("error_reporting", 1);
$DB_Host = "localhost";
$DB_Name="test";
$DB_Username="root";
$DB_Password="";

$con = mysql_connect($DB_Host,$DB_Username,$DB_Password) or die(mysql_errno());
$db = mysql_select_db("$DB_Name",$con) or die(mysql_error());
	

Change the “$DB_Name” if you choose different database name. Replace the database username at $DB_Username and password at $DB_Password. If you are working in localhost then no need to change. Now next step is function code.

3) Pagination Function Code

Finally, this is the main portion of this tutorial. Which defines Php pagination with a search function. As a result, we can fix custom pagination with search in our project. You just need to copy the function code and paste it in “header.php” OR “function.php” files. Because these common files included in the whole project. So, you can use a function in almost all project pages.

This function needs just four values.

1) CurrentPage : This is current page number.
2) TotalPages : Counted totla pages.
3) formName : Form name which is used to post CurrentPage and search string data.
4) linkClass : Class name for pagination CSS.


function setGPC($val,$act)
{
  if(!get_magic_quotes_gpc())
    $val = addslashes(trim($val));
	
  if($act == "display")
    $val = stripslashes($val);
	
  //return mysql_real_escape_string($val);
  return $val;
}

function DisplayPages($CurrentPage, $TotalPages, $formName, $linkClass)
{
if(!isset($formName))
	$formName = "frm1";

if(strlen(trim($linkClass)) > 0)
	$myDispClass = " class=\"".trim($linkClass)."\" ";
else
	$myDispClass = " ";

$_SERVER["SCRIPT_NAME"];
$Pagepos = strrpos($_SERVER["SCRIPT_NAME"],"/");
$keyPage = substr($_SERVER["SCRIPT_NAME"],$Pagepos+1);

echo "<script language=\"javascript\">";
echo "function gotoPage(a,l,frm)";
echo "{";
echo "frm = eval(\"document.\"+frm);";
echo "frm.action=l;";
echo "frm.cpage.value=a;";
echo "frm.submit();";
echo "}";
echo "</script>";

if($TotalPages>1)
{
echo "
<table width=\"99%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\" align=\"center\">
<tr> 
<td align=\"center\"><b><font face=\"Verdana\" size=\"1\">Page $CurrentPage of $TotalPages</font></b></td>
</tr>
</table>
";

echo "
<table width=\"95%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">
<tr> 
<td valign=\"top\" align=\"center\"><font face=\"verdana\" size=\"2\">";
if($CurrentPage>1)
{
	echo "<a".$myDispClass."href=\"javascript:gotoPage('1','$keyPage','$formName');\" 
	title=\"Go to first page\"
	onmouseover=\"javascript:return window.status='Go to first page';\"
	onmouseout=\"javascript:return window.status='';\">First</a>&nbsp;|&nbsp;
	<a".$myDispClass."href=\"javascript:gotoPage('".($CurrentPage-1)."','$keyPage','$formName');\" 
	title=\"Go to previous page (".($CurrentPage-1).")\"
	onmouseover=\"javascript:return window.status='Go to previous page (".($CurrentPage-1).")';\"
	onmouseout=\"javascript:return window.status='';\">Previous</a>&nbsp;|&nbsp;";
}
echo "Go to Page 
	<form style=\"display:inline;\"><input type=\"text\" name=\"cpage\" size=\"5\" value='".$CurrentPage."' class=\"inputnowidth\">&nbsp;
	<input type=\"button\" class=\"btn btn-primary\" name=\"btngo\" value=\"Go\" onclick=\"gotoPage(this.form.cpage.value,'$keyPage', '$formName');\">&nbsp;&nbsp;</form>";
if($CurrentPage<$TotalPages)
{
	echo "<a".$myDispClass."href=\"javascript:gotoPage('".($CurrentPage+1)."','$keyPage','$formName');\" 
	title=\"Go to next page (".($CurrentPage+1).")\"
	onmouseover=\"javascript:return window.status='Go to next page (".($CurrentPage+1).")';\"
	onmouseout=\"javascript:return window.status='';\">Next</a>&nbsp;|&nbsp;
	<a".$myDispClass."href=\"javascript:gotoPage('".$TotalPages."','$keyPage','$formName');\" 
	title=\"Go to last page\"
	onmouseover=\"javascript:return window.status='Go to last page';\"
	onmouseout=\"javascript:return window.status='';\">Last</a>";
}
echo "</font></td>
</tr>
</table>
";
}
}

Above all code snippet is our core key of pagination in PHP with the search filter. This function will get the required values and automatically create the pagination. Another advantage is search functionality. This function will work on search also and give search result with pagination. Also, Another advantage is you don’t need to fix other pagination for search.

4) PHP code

Below code snippet is our PHP code. In this code, we will fetch the data from the database with MySQL queries. In this code, you can see the “SELECT” query is used for fetch data. Also, we have to count the total rows of the result and apply the logic for pagination. Even more, the search query is also included in this code.


include('connection.php');
include('function.php');

$myCondition = Array();
if(isset($_REQUEST["name"]) && strlen($_REQUEST["name"]) > 0){
	$name = $_REQUEST["name"];
	array_push($myCondition," name LIKE '%".trim($name)."%' OR id LIKE '%".trim($name)."%'");
}
else
  $name = "";

if(count($myCondition) > 0)
	$myCondition = " WHERE (".implode(" AND ", $myCondition).")";
else
	$myCondition = "";

if(!isset($_REQUEST["cpage"]) || intval($_REQUEST["cpage"])==0)
$cpage=1;
else
   $cpage = $_REQUEST["cpage"];

$pagesize = 5; // No of results/rows
$startdisp = $pagesize*($cpage-1);
$qry .= "select * from demo $myCondition";
$qry .= " LIMIT $startdisp,$pagesize";
$count = "select count(*) from demo $myCondition";

$res = mysql_query($qry) or die ('Error :: in fetch data
'.mysql_error());
$total_res = mysql_num_rows($res);
$res_count = mysql_query($count) or die ('Error :: in count result
'.mysql_error());

if($tcount=mysql_fetch_array($res_count))
  $fcount = $tcount[0];
else
  $fcount = 1;

$TotalPages = ceil(($fcount)/$pagesize);
mysql_free_result($res_count);

5) HTML Code

In HTML code, first of all, we have to fetch all data from the database and print data in a table using “While Loop”. Rather, you can see in below code snippet. We have created two form in code. First is for search and second is for PHP pagination.


<form name="search_frm" id="search_frm" method="get" action="index.php" enctype="multipart/form-data">
<div>
	<input type="text" name="name" value="<?php echo setGPC($name,"display"); ?>"/>
	<button type="submit">Search</button>
	<input name="btnfilter" type="button" class="btn-blue" value="Clear Filter"
        onclick="javascript:window.location='index.php';">
</div>
</form>
<form name="frm1" method="get" id="frm1" action="index.php" enctype="multipart/form-data">
<table border="1" width="300">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
	<?php if($total_res>0){ ?>
	<?php while($row = mysql_fetch_array($res)){ ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
</tr>
	<?php }}else{ ?>
<tr>
<td colspan="2" align="center">No results found</td>
</tr>
	<?php } ?>
	<input type="hidden" name="cpage">
	<input type="hidden" name="name" value="<?php echo setGPC($name,"display")?>" />
</table>
</form>

6) Call function

Now finally we can call the function at the end of form code. You can see the below code for how to call the function or how to use a function. You have to place this code at the end of form in HTML code.


<?php DisplayPages($cpage,$TotalPages, "frm1","Admin_Link"); ?>

7) Full Project Code

Here is the full project code which includes the PHP code and HTML code together for pagination in PHP. Copy the code and paste it in “index.php” file. You also can download the full script at the bottom of the tutorial. Even more, we have created a demo also.


<?php 
	include('connection.php');
include('function.php');

$myCondition = Array();
if(isset($_REQUEST["name"]) &#038;&#038; strlen($_REQUEST["name"]) > 0){
	$name = $_REQUEST["name"];
	array_push($myCondition," name LIKE '%".trim($name)."%' OR id LIKE '%".trim($name)."%'");
}
else
	$name = "";

if(count($myCondition) > 0)
	$myCondition = " WHERE (".implode(" AND ", $myCondition).")";
else
	$myCondition = "";

if(!isset($_REQUEST["cpage"]) || intval($_REQUEST["cpage"])==0)
$cpage=1;
else
	$cpage = $_REQUEST["cpage"];

$pagesize = 5; // No of results/rows

$startdisp = $pagesize*($cpage-1);

$qry .= "select * from demo $myCondition";
$qry .= " LIMIT $startdisp,$pagesize";
$count = "select count(*) from demo $myCondition";

$res = mysql_query($qry) or die ('Error :: in fetch data
'.mysql_error());
$total_res = mysql_num_rows($res);
$res_count = mysql_query($count) or die ('Error :: in count result
'.mysql_error());

if($tcount=mysql_fetch_array($res_count))
	$fcount = $tcount[0];
else
	$fcount = 1;

$TotalPages = ceil(($fcount)/$pagesize);
mysql_free_result($res_count);
?>
<center>

<form name="search_frm" id="search_frm" method="get" action="index.php" enctype="multipart/form-data">
<div>
	<input type="text" name="name" value="<?php echo setGPC($name,"display"); ?>"/>
	<button type="submit">Search</button>
	<input name="btnfilter" type="button" class="btn-blue" value="Clear Filter" onclick="javascript:window.location='index.php';">
</div>
</form>

<form name="frm1" method="get" id="frm1" action="index.php" enctype="multipart/form-data">
<table border="1" width="300">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
	<?php if($total_res>0){ ?>
	<?php while($row = mysql_fetch_array($res)){ ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
</tr>
	<?php }}else{ ?>
<tr>
<td colspan="2" align="center">No results found</td>
</tr>
	<?php } ?>
	<input type="hidden" name="cpage">
	<input type="hidden" name="name" value="<?php echo setGPC($name,"display")?>" />
</table>
</form>
<?php DisplayPages($cpage,$TotalPages, "frm1","Admin_Link"); ?>
</center>

Download Script   View Demo

7) Conclusion

Using this pagination in PHP with search function you can easily fix pagination and search in your project. You just follow above all easy steps and as a result, you will get the wonderful functionality.

Releated Articles: