How to add Ajax on existing PHP & Mysql based pagination - php

Hi i am a new programmer,
i have a PHP & Mysql based pagination, i want to add Ajax functionality to it.
i have gone through many tutorials but i was not able to find any which tells about adding ajax onto existing pagination they all tell about making Ajax based pagination.
i want user be able to paginate even if javascript is turned off. so i want to add some Ajax to my code so that i can be able to paginate with Ajax and PHP.
i can use jquery .load() method to paginate.
please look at my code and suggest me how i can fetch page url for ajax to paginate
i guess something like this has to work. i cant figure out how, please help.
or tell me some tutorial i can learn from.
Jquery Code
$(document).ready(function(){
$('#pagination').click(function(){
$('pageurl').load('is-test2.php #PaginationDiv');});
});
PHP & MySQL Based Pagination
<?php
require_once('_ls-global/php/connection.php');
$db = mysql_select_db($database,$connection) or trigger_error("SQL", E_USER_ERROR);
$sql1 = "SELECT COUNT(*) FROM $table";
$result1 = mysql_query($sql1, $connection) or trigger_error("SQL", E_USER_ERROR);
$row = mysql_fetch_row($result1);
$numrows = $row[0];
$rowsperpage = 2;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$currentpage = (int) $_GET['page'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$sql2 = "SELECT * FROM internet_security ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result2 = mysql_query($sql2, $connection) or trigger_error("SQL", E_USER_ERROR);
$list = mysql_fetch_assoc($result2);
$startrow = ($currentpage-1) * $rowsperpage;
Code in html
h3>Results <?php echo ($startrow+1) ?> - <?php echo min($startrow + $rowsperpage, $row) ?> of <?php echo ($totalpages *$rowsperpage) ?></h3>
<ul><?php
if ($currentpage!=$totalpages) {
echo " <li><a href='{$_SERVER['PHP_SELF']}?page=$totalpages'>$totalpages</a></li> ";
$nextpage = $currentpage + 1;
echo " <li><a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>Next»»</a></li> ";
}?></ul>
<ul><?php
if($currentpage<$totalpages){
for ($x = ($currentpage - 3); $x < (($currentpage + 3) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <li id='pcurrent'><a href='{$_SERVER['PHP_SELF']}?page=$x'>$x</a></li>";
} else {
echo " <li><a href='{$_SERVER['PHP_SELF']}?page=$x'>$x</a></li> ";
}}}
}
}
?> </ul>
<ul><?php
if ($currentpage > 1){
$prevpage = $currentpage - 1;
echo " <li><a href='{$_SERVER['PHP_SELF']}?page=$prevpage'>««Prev</a></li> ";
echo "<li><a href='{$_SERVER['PHP_SELF']}?page=1'>1</a></li> ";
}?></ul>

since you are getting your page variable into the PHP script with GET method, you can pass the variable like :
$(document).ready(function(){
$('#pagination ul li a').click(function(){
e.preventDefault();
$('#divtoreplace').load($(this).attr("href"));
});
});

Related

php search pagination is not working

i can make pagination by query database and it works just fine. but when i use form to search from database, i can only get the first page data, the next page data won't show up.
i just cannot figure out how to maintain the search query..
this is my code. the problem should be in the url links in the pagination, but i just cannot see the problem
<?php
require('koneksi.php');
if(isset($_GET['search'])) {
$search = $_GET['search'];
$keyword = $_GET['keyword'];
$koneksi = mysqli_connect("localhost","root","","mycompany");
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM product WHERE deskripsi LIKE '%" . $keyword . "%'";
$result = mysqli_query($koneksi,$sql);
$rss = mysqli_fetch_row($result);
$numrows = $rss[0];
//numbers or rows to show per page
$rowperpage = 6;
//find out total pages
$totalpages = ceil($numrows/$rowperpage);
//get the current page or set default
if(isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page number
$currentpage = 1;
} // end if
// if the current page is greater than total pages...
if($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than total pages...
if($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowperpage;
$sql = "SELECT * FROM product WHERE deskripsi LIKE '%" . $keyword . "%' LIMIT $offset, $rowperpage";
$result = mysqli_query($koneksi, $sql);
// while there are rows to be fetched
while ($list = mysqli_fetch_assoc($result)) {
// echo data
echo $list['product_code'];
echo "<br>";
echo $list['deskripsi'];
}
/****** build the pagination links ******/
// range of num links to show
$range = 6;
$url = "searchbar.php";
// if not on page 1, don't show back links
if($currentpage > 1) {
// show << link to go to page 1
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=1'> << </a>";
//get previous page num
$prevpage = $currentpage - 1;
} // end if
echo " <li class='arrow'><a href='$url?currentpage=prevpage?&keyword=$keyword?cari=$cari'>«</a></li> ";
for($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it is a valid page number
if(($x > 0) && ($x <= $totalpages)) {
// if we are on current page
if($x == $currentpage) {
echo "<li class=''><a href=''> $x </a></li>";
} else {
// make it a link
//echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'> $x </a> ";
//echo "<li class=''><a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x </a></li>";
echo "<li class=''><a href='$url?currentpage=$x?&keyword=$keyword?cari=$cari'> $x </a></li>";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <li class='arrow'><a href='$url?currentpage=$nextpage?&keyword=$keyword?cari=$cari'>»</a></li> ";
// echo forward link for lastpage
// echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> >> </a> ";
} // end if
} // end if get search
require('footer.php');
?>
Looks like there could be a couple things missing here. For instance:
echo " <li class='arrow'><a href='$url?currentpage=prevpage?&keyword=$keyword?cari=$cari'>«</a></li> ";
in this line you are missing a $ for the prevpage: $prevpage but the querystring in the URL should only start with a ? and not contain question marks elsewhere, so this line should read more like
echo " <li class='arrow'><a href='$url?currentpage=$prevpage&keyword=$keyword&cari=$cari'>«</a></li> ";
I'm not 100% sure if that's going to fix your issue, but there is one big thing that I would ask you to look into before actually using this code anywhere and that's the SQL Injection that you have in your query.
You might read a bit of How can I prevent SQL injection in PHP? to get a better idea of how to rewrite your sql queries.
So, checkout your links, make sure the querystring is formatted correctly (http://host.com/script.php?querystring=something&var2=anothervar) where variables are separated only by &
As #aaronott pointed out, most of your links are wrong.
You are using cari=$cari which is not set anywhere, while in fact I guess you should add search=1 (or search=$search, but it's not really useful).
Also, you cannot have more than on ? in your querystring, so fix all your links like this:
...
if($currentpage > 1) {
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=1&search=1&keyword=$keyword'> << </a>";
$prevpage = $currentpage - 1;
}
echo " <li class='arrow'><a href='$url?currentpage=$prevpage&search=1&keyword=$keyword'>«</a></li> ";
...
if($x == $currentpage) {
echo "<li class=''><a href=''> $x </a></li>";
} else {
echo "<li class=''><a href='$url?currentpage=$x&search=1&keyword=$keyword'> $x </a></li>";
} // end else
...
echo " <li class='arrow'><a href='$url?currentpage=$nextpage&search=1&keyword=$keyword'>»</a></li> ";

show page numbering in PHP

I am using this coed in PHP to show next and previous buttons for records in a mysql database:
$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$MaxRowsPerPage = 25;
$total_records = mysql_num_rows($rs);
$total_pages = ceil($total_records / $MaxRowsPerPage);
if(isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
}
$start_from = ($page-1) * $MaxRowsPerPage;
$sql.=" LIMIT $start_from, $MaxRowsPerPage";
I am echoing $total_records to show the total amount, how can i show the number from and to on the current page. for example, on page 1 it will be showing records 1 to 25 (because max rows per page is 25) and then page 2 will be showing records 26 to 50 and so on...
There a are many ways of doing this, but here's a simple pagination example I made. It will also show 1-25, 26-50 etc. It's heavily commented so it should be easy to understand.
<?php
// Connect to database
include 'includes/db_connect.php';
// Find total number of rows in table
$result = mysql_query("SELECT COUNT(*) FROM example_table");
$row = mysql_fetch_array($result);
$total_rows = $row[0];
// Set rows per page
$rows_per_page = 25;
// Calculate total number of pages
$total_pages = ceil($total_rows / $rows_per_page);
// Get current page
$current_page = (isset($_GET['p']) && $_GET['p'] > 0) ? (int) $_GET['p'] : 1;
// If current page is greater than last page, set it to last.
if ($current_page > $total_pages)
$current_page = $total_pages;
// Set starting post
$offset = ($current_page - 1) * $rows_per_page;
// Get rows from database
$result = mysql_query("SELECT * FROM example_table LIMIT $offset, $rows_per_page");
// Print rows
echo '<hr>';
while($row = mysql_fetch_array($result))
{
echo $row['id'].'<br />';
echo $row['text'];
echo '<hr>';
}
// Build navigation
// Range of pages on each side of current page in navigation
$range = 4;
// Create navigation link for previous and first page.
if ($current_page > 1)
{
$back = $current_page - 1;
echo ' PREV ';
if ($current_page > ($range + 1))
echo ' 1... ';
}
else
echo ' PREV ';
// Create page links, based on chosen range.
for ($i = $current_page - $range; $i < ($current_page + $range) + 1; $i++)
{
if ($i > 0 && $i <= $total_pages)
if ($i == $current_page)
echo ' [<strong>'.$i.'</strong>] ';
else
echo ' '.$i.' ';
}
// Create navigation link for next and last page.
if ($current_page != $total_pages)
{
$next = $current_page + 1;
if (($current_page + $range) < $total_pages)
echo ' ...'.$total_pages.' ';
echo ' NEXT ';
}
else
echo ' NEXT ';
?>

Automatic pagination for status board program

i have more data's in my mysql database. i want to display the data, per page 10 data only i need to display, for this i wrote pagination code. its working very fine but i want to run that pagination automatically that means automatically after few seconds the page turns to second page then third page etc... but i don't know how to implement please help anyone. Here below the sample code for reference:
<?php
include "config.inc";
$sql = "SELECT COUNT(*) FROM test";
$result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
$rowsperpage = 3;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$sql = "SELECT * FROM test LIMIT $offset, $rowsperpage";
$result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_array($result)) {
echo $list['mark_cut_weld'] . " : " . $list['mark_cut_inves'] . "<br />";
}
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
$prevpage = $currentpage - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " [<b>$x</b>] ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
}
?>
Above code, i just fetch the data from mysql database by php. then set the data per page is 3. i just get the total count and then divide by number of rows into rows per page... then automatically it will display the data.
My target is display the data from database. per page 10 data's and then automatically it move to next page for next 10 data without any action click or submit...
Because it is status board program.. we going to display by big tv in factory... so workers can see the status of the work in this big tv.
You can set a header redirect to redirect to next page.
For example the following code will redirect you to next page in 10 seconds.
header('Refresh: 10; URL='.$_SERVER['PHP_SELF'].'?page='.$next_page);
Make sure you set the header before you echo anything in PHP.
You are going to want to use javascript to set timeouts that will redirect the location to the next page every so often.
For example, add this to the bottom of your HTML body:
<script type="text/javascript">
function switchPage(){
window.location = "<?php echo $next_page?>"; // set the next page of results to view.
}
setTimeout(switchPage,60*1000); // call callback every minute
</script>
The variable $next_page will need to be a URL to the next set of results using PHP.
To have it repeat you will need a modulus on the PHP side that flips back to page 0 when the end of the results has been reached.
<?php
$next_page_count = ++$currentpage % $totalpages;
$next_page = $_SERVER['PHP_SELF'] . '?currentpage=' . $next_page_count;

Integrating pagination into mysql query

I have the following mysql query and I have added pagination from here:
http://www.tonymarston.net/php-mysql/pagination.html
$DBQuery3 = mysqli_query($dblink, "SELECT * FROM images WHERE project_id = '$FormProjectID'");
if (mysqli_num_rows($DBQuery3) < 1) {
$ProjectContent = '
<p>This project is empty. Upload some files to get started.</p>
';
} else {
//if no page number is set, start at page 1
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
//This code will count how many rows will satisfy the current query.
$DBQuery3b = mysqli_query($dblink, "SELECT count(*) FROM images WHERE project_id = '$FormProjectID'");
$query_data = mysqli_fetch_row($dblink, $DBQuery3b);
$numrows = $query_data[0];
//This code uses the values in $rows_per_page and $numrows in order to identify the number of the last page.
$rows_per_page = 2;
$lastpage = ceil($numrows/$rows_per_page);
//This code checks that the value of $pageno is an integer between 1 and $lastpage.
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
//This code will construct the LIMIT clause for the sql SELECT statement.
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$DBQuery3c = "SELECT * FROM images WHERE project_id = $FormProjectID $limit";
$DBQuery3d = mysqli_query($dblink, $DBQuery3c);
//set this variable to empty and so we can latwe loop and keep adding images to it
$ProjectContent ='';
while($row = mysqli_fetch_array($DBQuery3d)) {
$DBImageID = $row['image_id'];
$DBProjectID = $row['project_id'];
$DBImageName = $row['image_name'];
$DBImageDescription = $row['image_description'];
$DBDateCreated = $row['date_created'];
$DBLinkToFile = $row['link_to_file'];
$DBLinkToThumb = $row['link_to_thumbnail'];
$DBGivenName = $row['given_name'];
//if the image was given a name by the user, display it
//otherwise display the generated name
if (strlen($DBGivenName) > 1) {
$FileName = $DBGivenName;
} else {
$FileName = $DBImageName;
}
$ProjectContent .= '
<img src="uploads/'.$DBLinkToThumb.'" width="150px" height="150px" alt="'.$FileName.'" title="'.$FileName.'"/>
';
//Finally we must construct the hyperlinks which will allow the user to select other pages. We will start with the links for any previous pages.
if ($pageno == 1) {
$FirstPrev = " FIRST PREV ";
} else {
$First = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=1'>FIRST</a> ";
$prevpage = $pageno-1;
$Prev = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$prevpage'>PREV</a> ";
}
//Next we inform the user of his current position in the sequence of available pages.
$PageNumb = " ( Page $pageno of $lastpage ) ";
//This code will provide the links for any following pages.
if ($pageno == $lastpage) {
$NextLast = " NEXT LAST ";
} else {
$nextpage = $pageno+1;
$Next = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$nextpage'>NEXT</a> ";
$Last = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$lastpage'>LAST</a> ";
}
}
}
Then in my html I have:
<div id="projectview">
<?php echo $ProjectContent; ?>
<?php echo $FirstPrev; ?>
<?php echo $First; ?>
<?php echo $Prev; ?>
<?php echo $PageNumb; ?>
<?php echo $NextLast; ?>
<?php echo $Next; ?>
<?php echo $Last; ?>
<div class="clear-div"></div>
</div>
This is outputing for example in this case 2 images, but the pagination links look like this:
FIRST PREV ( Page 1 of 0 ) NEXT LAST
Clicking on the links is not cycling through any other images, it still shows the same 2 images.
I can't figure out what I have done wrong here. I don't understand why it says "1 of 0" when clearly there should be more results.

PHP-Modifing Pagination for Sorting

Hi i am a new programmer.
i have a simple pagination which works fine,
i have sorting options for sorting my recordset result by id, title etc which is also working fine, the codes are below.
now i want to combine both and have a functionality that pagination should work on both conditions.
that is when recordset result is displayed by default pagination should work as before.
and when recordset result is sorted by options pagination should work on sorted result too.
i got something figured out, the codes are below, but i cant get it to work.
my code for recordset and basic pagination-sorting are:
<?php
$table='mytable';
$pagename = "is-test.php";
$db = mysql_select_db($database,$connection) or trigger_error("SQL", E_USER_ERROR);
$sql1 = "SELECT COUNT(*) FROM $table";
$result1 = mysql_query($sql1, $connection) or trigger_error("SQL", E_USER_ERROR);
$row = mysql_fetch_row($result1);
$numrows = $row[0];
$rowsperpage = 5;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$currentpage = (int) mysql_real_escape_string($_GET['page']);
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$orderBy = array('id', 'title',);
$order = '';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = mysql_real_escape_string($_GET['orderBy']);
}else{
$order='id';
}
$offset = ($currentpage - 1) * $rowsperpage;
$sql2 = "SELECT * FROM $table ORDER BY $order ASC LIMIT $offset, $rowsperpage";
$result2 = mysql_query($sql2, $connection) or trigger_error("SQL", E_USER_ERROR);
$list = mysql_fetch_assoc($result2);
$startrow = ($currentpage-1) * $rowsperpage
my codes for sorting options:
Sort by
id:
title:
my codes for pagination are:
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo " <li><a href='$pagename?page=$nextpage'>Next»»</a></li> ";
}
if($currentpage<$totalpages){
for ($x = ($currentpage - 3); $x < (($currentpage + 3) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <li id='pcurrent'><a href='$pagename?page=$x'>$x</a></li>";
} else {
echo " <li><a href='$pagename?page=$x'>$x</a></li> ";
}}}
}
if ($currentpage > 1){
$prevpage = $currentpage - 1;
echo " <li><a href='$pagename?page=$prevpage'>««Prev</a></li> ";
}
upto now everytthing is working except pagination only paginate defaut recordset resunt not sorted recordset result for that i have to change url parameter for pagination to work on sorting result,
so i have changed my pagination links as
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo " <li><a href='$pagename?orderBy=$order,page=$nextpage'>Next»»</a></li> ";
}
if($currentpage<$totalpages){
for ($x = ($currentpage - 3); $x < (($currentpage + 3) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <li id='pcurrent'><a href='$pagename?orderBy=$order,page=$x'>$x</a></li>";
} else {
echo " <li><a href='$pagename?orderBy=$order,page=$x'>$x</a></li> ";
}}}
}
if ($currentpage > 1){
$prevpage = $currentpage - 1;
echo " <li><a href='$pagename?page=$prevpage'>««Prev</a></li> ";
}
i.e added orderBy=$order in links for pagination, but pagination is not working now,
not on default recordset result and not on sorted recordset result.
please see what i am doing wrong
I didn't read the whole code but you have at least one error in your query string. Each GET-parameter should be separated by "&" instead of "," what you did. Changing your code from
'?orderBy=$order,page=$nextpage'
to
'?orderBy=$order&page=$nextpage'
should fix this error at least.
You should put error_reporting(E_ALL); at the beginning of your code to see notices from php (which would have helped you a lot). If it's still not working afterwards you should debug your GET params with
<?php var_dump($_GET); ?>

Categories