I have following code to display only 10 records at one page. When I load the page for the first time, first 10 records are displayed well (see screenshot)
. But when I click on "Next 10 records", the same URL is not loaded with extra GET parameters using $_SERVER['PHP_SELF'].
My address bar shows this instead:
http://localhost/PHP/$_SERVER['PHP_SELF']?page=$page
Here is my complete code;
<?php
$con = #mysqli_connect( "localhost:3306", "root", "P#ssw0rd", "world" ) or die ("Couldn't connect to server");
//get total number of records
$query = "SELECT count(ID) FROM city";
$result = mysqli_query ( $con, $query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
$rec_count = mysqli_num_rows($result);
$rec_limit = 10; //number of records to display
if( isset($_GET['page']) ){ //when user clicks link
$page = $_POST['page'] + 1; //page count increment by 1
$offset = $rec_limit * $page;
}
else{ //user has not yet clicked any link
$page = 0;
$offset = 0;
}
//xxxxxxxx $rec_count is taken from result set
$left_rec = $rec_count - ($page * $rec_limit); //number of records remaining to display
$display_query = "SELECT * FROM city LIMIT $offset, $rec_limit";
$display_result = mysqli_query ( $con, $display_query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
echo "<table>";
echo "<th>ID</th> <th>Name</th> <th>Country Code</th> <th>District</th> <th>Population</th>";
while( $row = mysqli_fetch_assoc($display_result) ){
extract($row);
echo "<tr>
<td>$ID</td>
<td>$Name</td>
<td>$CountryCode</td>
<td>$District</td>
<td>$Population</td>
</tr>";
}
echo "</table>";
if( $page == 0 ){ //user has not yet clicked any link
echo ' Next 10 records ';
}
else if( $page>0 ){ //user has clicked at least once on link
$last = $page - 2; //here -2 because, in isset block again increment by 1
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$last> Last 10 records </a>';
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$page> Next 10 records </a>';
}
else if( $left_rec < $rec_limit ){ //when only records less than 10 remains
$last = $page - 2;
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$last> Last 10 records </a>';
}
?>
if( $page == 0 ){ //user has not yet clicked any link
echo ' Next 10 records ';
}
This will fix your single and double quotes and will echo the values instead of the variables. You have to apply the same logic to all the inputs.
You can also do:
if( $page == 0 ){ //user has not yet clicked any link
echo " Next 10 records ';
}
echo ' Next 10 records ';
And similar $last.
Related
I want to read the different ID on different page, by using the prev/next button.
If I click next button, I want to get the next ID, if I click previous button, it will back to the previous ID. Following is what I want.
Example:
testnext_pre1.php?id=1&page=1
testnext_pre1.php?id=2&page=2
testnext_pre1.php?id=5&page=3
Here is my problem. As you can see, I get the same ID on every page because of my code. How to get the correct ID for the page?
Please take note: the IDs are not increase by sequence, as some contents might be deleted. So I don't want the answer something like "+1".
$rowsPerPage = 1;
if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
{
$pageNum = 1;
}
// preceding rows
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM news LIMIT $previousRows, $rowsPerPage";
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
// print the results
while(list($id,$name,$pass,$perm,$email,$date) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$name</td><td>$pass</td><td>$perm</td><td>$email</td>
<td>$date</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(id) AS numrows FROM news";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = "<div class=\"paginationbtn floatleft\">previous</div>";
$first = " [First Page] ";
}
else
{
$prev = ' previous ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$resultid = mysql_query("SELECT id FROM news");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
}
else
{
$next = ' [Next] ';
}
echo $prev . " " . $next;
Just get the previous and next ids from the database
if ($pageNum > 1)
{
//Get previous id using this query
SELECT id FROM news LIMIT $previousRows-1, $rowsPerPage
}
if ($pageNum < $lastPage)
{
//Get next id using this query
SELECT id FROM news LIMIT $previousRows+1, $rowsPerPage
}
Try the following sql query to get the next id,right now you are looping the news table and your next button will always have the same value
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$resultid = mysql_query("select id from news where id = (select min(id) from news where id > ".$_GET['id'].")");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
$prevresultid = mysql_query("select id from news where id = (select max(id) from news where id < ".$_GET['id'].")");
while($loopid=mysql_fetch_array($prevresultid))
{
$rowid = $loopid['id'];
$prev= " <div class=\"paginationbtn floatleft\">next</div> ";
}
}
Note: you will need mysqli and prepared statements to secure your code
if you want to set pagination than no need of next id it will mange by query only . and in query we change only offset .
for e.g each page display 3 records so our limit is 3
now if we on first page than our fetch record query is(on first page offset is always 0)
so offset is 0 and limit is 3
SELECT fieldName FROM tableName LIMIT offset,limit
for second page now current offset is 3 so
prev is current_offset minus limit (3-3) so prev offset is 0
next is current_offset plus limit (3+3) so next offset is 6
now in 3rd page current offset is 6
prev is current_offset minus limit (6-3) so prev offset is 3
next is current_offset plus limit (6+3) so next offset is 9
try this one
<?php
$rowsPerPage = 1;
if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
{
$pageNum = 1;
}
// preceding rows
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM news LIMIT $previousRows, $rowsPerPage";//offset,limit
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
// print the results
while(list($id,$name,$pass,$perm,$email,$date) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$name</td><td>$pass</td><td>$perm</td><td>$email</td>
<td>$date</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(id) AS numrows FROM news";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($pageNum > 1)//current page > 1
{
$page = $pageNum - 1;
$prev = "<div class=\"paginationbtn floatleft\">previous</div>";
$first = " [First Page] ";
}
else
{
$prev = ' previous ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$next_row=$previousRows+1;
$resultid = mysql_query("SELECT id FROM news LIMIT $next_row,1");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
}
else
{
$next = ' [Next] ';
}
echo $prev . " " . $next;
I want to display five record per page through pagination (mysql,php,html,css) until all the records are displayed, navigation to pages must be like, Page: 1 2 3 4 5 6 7 7 8... Last.
HERE IS MY CODE TO VIEW ALL THE RECORDS FROM emp_master table.
I am new to PHP so please write an easily understandable code for pagination. I have seen few examples but they are not working.
<?php
$con=mysqli_connect("localhost","user","password","dataplus");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM emp_master");
echo "<table border='1'>";
$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
I want to display five record per page through pagination untill all the records are displayed, navigation to pages must be like, Page: 1 2 3 4 5 6 7 7 8... Last.
This code below is not working:
$dbhost="localhost";
$dbuser="10053";
$dbpass="n6867242";
$database="0368";
$rec_limit = 10;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('1005368');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM emp_master ";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) ) {
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}else {
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT emp_id, emp_name, e_mail ".
"FROM emp_master ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP MAIL : {$row['e_mail']} <br> ".
"--------------------------------<br>";
}
if( $page > 0 ) {
$last = $page - 2;
echo "Last 10 Records |";
echo "Next 10 Records";
}else if( $page == 0 ) {
echo "Next 10 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 10 Records";
}
mysql_close($conn);
If you want just PHP MySQL code, I usually use something like the following.
$page=max(intval($_GET['page']),1); // assuming there is a parameter 'page'
$itemsperpage = 5;
$total=100; // total results if you know it already otherwise use another query
$totalpages = max(ceil($total/$itemsperpage),1);
$query = "SELECT * FROM emp_master LIMIT ".(($page-1)*$itemsperpage).",".$itemsperpage; // this will return 5 items based on the page
You can use a library called dataTables that will auto paginate the data and you can easily customize it to suit your needs with the look and how many records to show per page. It also has a search field which enables users to search your data without any extra code.
All you have to do is include a couple of cdn's and the following code and everything works fine
$(document).ready(function(){
$('#myTable').DataTable();
});
Some examples here
you just should remove spaces in href and also make $page = $page + 1 when page is 0
if( $page > 0 ) {
$last = $page - 2;
echo "Last 10 Records |";
echo "Next 10 Records";
}else if( $page == 0 ) {
$page = $page + 1;
echo "Next 10 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 10 Records";
}
Link is here for demo, click here to experience the result
Here is the code working for me, just change your db name, username and password
and get pagination done. You can change $rec_limit value to your desired no. of records per page.
<?php
$host="localhost";
$username="68";
$password="67242";
$database="68";
$rec_limit = 5;
$conn = mysql_connect($localhost,$username,$password);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('10');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM emp_master ";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) ) {
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}else {
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT eid,ename, email, quali, gender, contactno, birthdate, joiningdate,CURDATE(), TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) ) AS age ".
"FROM emp_master ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
echo "<table border='1'>";
$i = 0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
if( $page > 0 ) {
$last = $page - 2;
echo "Last 5 Records | ";
echo "Next 5 Records";
}else if( $page == 0 ) {
$page = $page + 0;
echo "Next 5 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 5 Records";
}
mysql_close($conn);
php?>
IF your are using mysqli the code is below
$conn=mysqli_connect("localhost","root","","ui");
$start=0;
$limit=5;
$t=mysqli_query($conn,"select * from form_table");
$total=mysqli_num_rows($t);
if(isset($_GET['id']))
{
$id=$_GET['id'] ;
$start=($id-1)*$limit;
}
else
{
$id=1;
}
$page=ceil($total/$limit);
$query=mysqli_query($conn,"select * from form_table limit $start, $limit");
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script s src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
</head>
<body>
<div class="container">
<h2>Table</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Hobbies</th>
<th>Course</th>
</tr>
</thead>
<tbody>
<?php
while($ft=mysqli_fetch_array($query))
{?>
<tr>
<td><?= $ft['0']?></td>
<td><?= $ft['1']?></td>
<td><?= $ft['2']?></td>
<td><?= $ft['3']?></td>
<td><?= $ft['4']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<ul class="pagination">
<?php if($id > 1) {?> <li>Previous</li><?php }?>
<?php
for($i=1;$i <= $page;$i++){
?>
<li><?php echo $i;?></li>
<?php
}
?>
<?php if($id!=$page)
{?>
i Give you an example of my project of pagination. Just you have to put your values in the code
$sql="SELECT * FROM tblname LIMIT $next,5";
$results = mysqli_query($conn,$sql);
}
else if (isset($_POST['prev']))
{
$prev1=$_POST['prev'];
$next=$_POST['prev'];
$prev=$prev1;
$sql="SELECT * FROM tablename LIMIT $prev,5";
$prev=$prev1;
$results = mysqli_query($conn,"SELECT * FROM tablename LIMIT $prev,10");
if($prev==0)
{
$prev = 0;
}
else
{
$prev=$next-10;
}
}
else
{
$next=0;
$prev=0;
$results = mysqli_query($conn,"SELECT * FROM tablename LIMIT $next,10");
}
I want to use pagination on sql fetched row. I am using this code:
<?php
$rec_limit = 4;
$sql = "SELECT count(id) FROM wp_wct8 ";
$retval = mysql_query( $sql);
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) ) {
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}else {
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT id, name, insurance ".
"FROM wp_wct8 ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql);
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while ($b = mysql_fetch_array($retval)){
echo $b['name'];
echo $b['insurance'];
}
if( $page > 0 ) {
$last = $page - 2;
echo "Last 4 Records |";
echo "Next 4 Records";
}else if( $page == 0 ) {
echo "Next 4 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 4 Records";
}
?>
but pagination not working... when i click on show next 4 records it is showing same records not next..please helpme... thanks in advance
I don't recommend you to put this code online as it's vulnerable to SQL injection. (Use prepared statements with PDO instead or at least, escape your input in the SQL query.)
I assume the error are the whitespaces in your links. So try removing the whitespaces, e.g. echo "Last 4 Records |";
I've the following Pagination code :
$rec_limit = 3;
/* Get total number of records */
$query = "SELECT count(id) FROM news";
$result = mysql_query($query);
if(!$result)
{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($result, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$query2 = "SELECT * ".
"FROM news ".
"LIMIT $offset, $rec_limit";
$result2 = mysql_query( $query2 );
if(! $result2 )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($result2, MYSQL_ASSOC))
{
echo " ID :{$row['id']} <br> ".
" News : {$row['title']} <br> ".
" Date : {$row['date']} <br> ".
"--------------------------------<br>";
}
if( $page > 0 )
{
$last = $page - 2;
echo "Last 3 Records |";
echo "Next 3 Records";
}
else if( $page == 0 )
{
echo "Next 3 Records";
}
else if( $left_rec < $rec_limit )
{
$last = $page - 2;
echo "Last 3 Records";
}
The code works perfectly as needed, except that the a href part where it shows the Next 3 records link even when there is no news left. By that i mean, it keeps opening up pages with empty records ! How can i remove Next 3 Records link when it reaches the last news ID.
Thank You
Just bring the last condition above the other two and change < to <=:
if($left_rec <= $rec_limit)
{
$last = $page - 2;
echo "Last 3 Records";
} else if ( $page > 0 )
{
$last = $page - 2;
echo "Last 3 Records |";
echo "Next 3 Records";
}
else if( $page == 0 )
{
echo "Next 3 Records";
}
I am having issues with some pagination with data i get from a MySQL database in PHP.
My code is below. Basically what happens is it creates the right amount of pages however each page shows the same data and doesn't even show only 5 rows per page.
I'm really stuck. This is my first time trying pagination. Any help would be greatly appreciated.
$pagenum = $_GET['pagenum'];
if (!(isset($pagenum)))
{
$pagenum = 1;
} else
{
$pagenum = $_GET['pagenum'];
}
//Count the number of results.
$data = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id'") or die(mysql_error());
$rows = mysql_num_rows($data);
//Set the number of results to be displayed per page.
$page_rows = 5;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
} elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'LIMIT ' . ($pagenum - 1) * $page_rows .',' .$page_rows;
//This is the query again, the same one... the only difference is we add $max into it.
$data_p = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id' '$max'") or die(mysql_error());
//Work out writers earnings based on prices.
//100 Words - $1.25
//300 Words - $2.50
//500 Words - $4.00
//700 Words - $5.50
//1000 Words - $8.00
$_100earnings = "0.65";
$_300earnings = "1.25";
$_500earnings = "2.50";
$_700earnings = "3.00";
$_1000earnings = "5.00";
?>
<!-- main -->
<div id="main">
<center><h2>Write Articles</h2></center>
<br />Available Projects:
<table border="1">
<tr>
<td>Title:</td>
<td>Length:</td>
<td>Writers Earnings:</td>
</tr>
<?php
//This is where you display your query results
while($info = mysql_fetch_array($data_p))
{
echo "<tr>";
echo "<td>" . $info['keywords'] . "</td>";
echo "<td>" . $info['length'] . "</td>";
switch ($info['length'])
{
case 100:
$writersearnings = $_100earnings;
break;
case 300:
$writersearnings = $_300earnings;
break;
case 500:
$writersearnings = $_500earnings;
break;
case 700:
$writersearnings = $_700earnings;
break;
case 1000:
$writersearnings = $_1000earnings;
break;
}
echo "<td>$" . $writersearnings . "</td>";
//echo $info['Name'];
echo "</tr>";
}
?>
</table>
<br /><br />
<?php
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
} else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
} else
{
$next = $pagenum + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
use this code, remove ' around $max in query, when you add ' around $max the query becomes select.... from.... where..... 'LIMIT.....' and it fails the query.
$data_p = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id' $max") or die(mysql_error());
You need to specify LIMIT in your query LIMIT offset,count
$data_p = mysql_query("SELECT * FROMarticlesWHEREcontent= '' ANDrequestedby!= '$id' '$max'") or die(mysql_error());
Remove the ' quotes from '$max'
$data_p = mysql_query("SELECT * FROM articles WHERE content= '' AND requestedby!= '".$id."' ".$max) or die(mysql_error());