I have a MySql query with a simple pagination AddOn, that shows just a next and previous.
The problem I am having is that when it rolls in the next page it just shows the more button but no data. If I check to see the value of page total pages it doesn't have a value. Below is my code. This isn't perfect but I am just trying to build it myself and so any pointers would be appreciated.
Thanks
$tableName="data";
$targetpage = "exact.php";
$limit = 5;
$type = $_GET['type'];
$man = $_GET['manufacturer'];
$model_group = $_GET['model_group'];
$year = $_GET['year'];
$query = "SELECT COUNT(*) as num FROM $tableName where engine='$type' AND
manufacturer='$man' and model_group='$model_group' and '$year' BETWEEN start_year AND
end_year;";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages['num'];
$stages = 3;
$page = mysql_escape_string($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
// Get page data
$query1 = "SELECT * from $tableName where engine='$type' AND manufacturer='$man' and model_group='$model_group' and '$year' BETWEEN start_year AND end_year LIMIT $start, $limit";
$result = mysql_query($query1);
// Initial page num setup
if ($page == 0){$page = 1;}
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages/$limit);
$LastPagem1 = $lastpage - 1;
if ($page > 1){
echo "<a href='$targetpage?page=$prev&type=$type&manufacturer=$manufacturer&year=$year'><div class='previous'><img src='images/PrevButton1.fw.png' width='108' height='58' style='border: none;'/></span></a>";
}else{}
if ($page < $lastpage){
echo "<a href='$targetpage?page=$next&type=$type&manufacturer=$manufacturer&year=$year&model_group=$model_group'><div class='next'><img src='images/MoreButton1.fw.png' width='108' height='58' style='border: none;'/></span></a>";
}else{}
You save manufacturer to variable $man:
$man = $_GET['manufacturer'];
but in the link you use (empty) variable $manufacturer
echo "<a href='$targetpage?page=$prev&type=$type&manufacturer=$manufacturer&year=$year'><div class='previous'><img src='images/PrevButton1.fw.png' width='108' height='58' style='border: none;'/></span></a>";
The Pagination worked fine, i just noticed that the manufacturer variable in the next and prev buttons was spelt wrong and this caused the problem so the code above works fine for a basic pagination script.
Related
I have a little script that have a Previous & Next button.
My problem is I want to detect & place the ID in those buttons
this is the code from the pagination
<body>
<?php include_once 'data.php'; ?>
<center>
<ul class="pagination">
<?php
if($page_counter == 0){
echo "<li><a href=?start='0' class='active'>0</a></li>";
for($j=1; $j < $paginations; $j++) {
echo "";
}
}else{
echo "<a href=?start=$previous><button>Previous</button></a>";
for($j=0; $j < $paginations; $j++) {
if($j == $page_counter) {
echo " ";
}else{
echo " ";
}
}if($j != $page_counter+1)
echo "<a href=?start=$next><button>Next</button></a>";
}
?>
</ul>
</center>
In this part I have the ID but the problem is I can`t get it with this example to place it into the pagination.
<?php
foreach($result as $row) {
echo '
<div class="card"><button1>
'. $row['notice_id'] .'
<div class="time-left">
<div class="dropdown1">
' ;
}
}
else {
echo '';
}
$conn->close();
?>
</div></div>
This is the code from data.php I think I need to place some code into for detection from the ID
<?php
//include configuration file
require 'configuration.php';
$start = 0; $per_page = 1;
$page_counter = 0;
$next = $page_counter + 1;
$previous = $page_counter - 1;
if(isset($_GET['start'])){
$start = $_GET['start'];
$page_counter = $_GET['start'];
$start = $start * $per_page;
$next = $page_counter + 1;
$previous = $page_counter - 1;
}
// query to get messages from messages table
$q = "SELECT * FROM group_notice LIMIT $start, $per_page";
$query = $db->prepare($q);
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
// count total number of rows in students table
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
// calculate the pagination number by dividing total number of rows with per page.
$paginations = ceil($count / $per_page);
?>
You can use some formulas for calculate limit and offset of results.
For example you have 100 records, and you want to paginate it into 10 records per page, and the formula is like below.
// Get Page from Query String
$page = 1;
if(!empty($_GET["page"])){
$page = $_GET["page"];
}
// Get record count
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
$per_page = 10; // records per page
$pages = ceil($count/$per_page); // get total page
$start = $page * $per_page - $per_page; // get offset
// Do something with your records
$query = db->prepare("SELECT * FROM group_notice LIMIT ?, ?");
$query->bind_param("ii", $start, $per_page); // you should use bind param if you use prepared statement
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
if($page > 1){
echo 'Prev'; // Print Prev Page
}
for($i = 1; $i <= $pages){
echo ''.$i.''; // Print Page Number
}
if($page < $pages){
echo 'Next'; // Print Next Page
}
Hope it helps.
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'm trying to do pagination in PHP, everything seems to be working, except that next and previous links don't work, it's only when I manually insert the page number in the URL that it displays data from the database on the next page.
Here is my code:
This is where I initialised the perpage and page. These are at the beginning of the page.
<?php
$per_page=4;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page=1;
}
$page;
echo $start_from = ($page-1) * $per_page;
//$search = $_POST['search'];
?>
And this is for the next and previous links, those ones that display the results depending on what the user wants to see.
<?php
$query = "select * from services";
$result = mysqli_query($link, $query);
$total_records = mysqli_num_rows($result);
//Using ceil function to divide the total records on per page
$total_pages = ceil($total_records / $per_page);
$prev = $page - 1;
if($page == 1){
echo "<span align='right' class='inactive'>← Prev</span>";
}else{
echo "<a href='livebands.php?page=$prev'><span class='paging-prev'>".'← Prev'."</span></a>";
}
for ($i=1; $i<=2; $i++) {
for ($i=1; $i<=$page; $i++) {
echo "<a href='livebands.php?page=$i'><span class='paging'>" .$i. "</span></a>";
}
}
$page++;
if ($page>$total_pages){
echo "<span align='right' class='inactive'>→ Next</span>";
}else{
echo "<a href='livebands.php?page=$page&per_page=$per_page'><span align='right' class='paging-next'>".'Next →'."</span></a>";
}
?>
If I use you code and hardcode the $total_records variable to 5 for example, the links seem to work.
// $query = "select * from services";
// $result = mysqli_query($link, $query);
// $total_records = mysqli_num_rows($result);
$total_records = 5;
Are you sure that your $total_records is more than 4?
I have few records in MySQL DB table.
Displayed those records with pagination PREV and NEXT.
Page ids are displaying in url bar.
http://localhost/pagination.php?page=5
I don't want them while pagination clicking.
How can i do this?
Here is my code.
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("moodle");
$per_page = 10;
$pages_query = mysql_query("SELECT COUNT('id') FROM question");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysql_query("SELECT * FROM question LIMIT $start, $per_page");
while($query_row = mysql_fetch_assoc($query)){
echo $query_row['id']."<br />";
}
$prev = $page - 1;
$next = $page + 1;
echo "<a href='pagination.php?page=$prev'>Prev</a> ";
if($pages >= 1){
for($x=1; $x<=$pages; $x++){
echo ''.$x.' ';
}
}
echo "<a href='pagination.php?page=$next'>Next</a> ";
?>
Use id in session and don't display it in url . other method is to use Ajax call in pagination on click of previous or next button . i think these are two simple solutions for you that you can easily manage .
I tried so many different solutions. Im new to php since 1 week, used ASP 12 years ago so I hope I can get some help.
Everything down here works fine. But there are around 1000 rows in the db and I need to split them up in pages.
<?php
$con = mysqli_connect("localhost","test","test","test")or die('could not connect to database');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<table border='0'>
<tr>
<th>Img:</th>
<th>Text:</th>
</tr>";
$result = mysqli_query($con,"SELECT Jokes.ID, Categories.CategoryName, Jokes.CategoryID, Jokes.JokeText FROM Jokes LEFT JOIN Categories ON Jokes.CategoryID = Categories.ID ORDER BY Jokes.JokeText");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td align='center'><img src='webimg/" . $row['CategoryName'] . ".png' height='35' width='35'></td>";
echo "<td align='left' width='80%'>" . $row['JokeText'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Kind Regards.
You can use MySQL LIMIT for that.
I've used to do it like this:
Get the total number of rows you're paging and have a parameter like in the URL, i.e. "/p/5" or ?page=5 (I will use this for reference, easier to write code and for you to understand) for page no. 5, also do a failsafe, like this:
Say you have 10 records per page:
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$records_per_page = 10;
And, in your SQL you will have something like this
$start = ($page-1) * $records_per_page;
$result = mysql_query("select * from table limit {$start}, {$records_per_page}");
Kind of crude, but you should get the point and be on the right path.
For building your pagination links... that's totally up to you. You should get the total amount of rows with a "select count (PRIMARY_KEY) from table" query prior, so you can calculate the max number of pages.
What you're searching for is the LIMIT of mysql.
The usage is very simple.
For example:
"SELECT * FROM tablename LIMIT 3"
This will give you the first three results.
In your case, you need an offset, depends on the current page:
"SELECT * FROM tablename LIMIT offset,results"
The offset can be calculated, depends on how many results you want each page.
"SELECT * FROM tablename LIMIT 20,10"
This will display 10 results, start at result 20. This could be for the 3. site if you want 10 results each site.
<?php
$per_page = 10; //no. of results to display in one page
$pages_query = mysql_query("SELECT COUNT('id') FROM JOKES");//Or whatever field. this is just to check the number of results.
$pages = ceil(mysql_result($pages_query, 0) / $per_page);//to get the total no. of pages that will be there. For example if u have 60 results than no. og pages will be 60/10=6
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;// if the page variable in your url is set that means that u have clicked a page number. So it will be taking that page number and displaying those results
$start = ($page - 1) * $per_page;//to get the starting result of that page. If you are in say 6th page, then the starting element would be 6-1*10=50. This makes sure that the results in the previous pages are not displayed
$query = mysql_query("SELECT * FROM JOKES LIMIT $start, $per_page");//set the limit of results that page
while($query_row = mysql_fetch_assoc($query)){
echo " ur table names ";
}
$prev = $page - 1;//to set the prev page variable
$next = $page + 1;//to set the next page variable
if(!($page<=1)){
echo "<a href='Yourpagename.php?page=$prev'>Prev</a> ";
}//does not displays the prev variable if you are already one first page
if($pages>=1 && $page<=$pages){
for($x=1;$x<=$pages;$x++){
echo ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
}//display all the pages. Display the current page as bold
}
if(!($page>=$pages)){
echo "<a href='Your page name.php?page=$next'>Next</a>";
}//do not display next vvariable if your are in the last page
?>
Thx for all the answers. I came over this tutorial and it worked: http://www.developphp.com/view.php?tid=1349
<?php
include_once("mysqli_connection.php");
$sql = "SELECT COUNT(id) FROM testimonials WHERE approved='1'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 10;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, firstname, lastname, datemade FROM testimonials WHERE approved='1' ORDER BY id DESC $limit";
$query = mysqli_query($db_conx, $sql);
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$datemade = $row["datemade"];
$datemade = strftime("%b %d, %Y", strtotime($datemade));
$list .= '<p>'.$firstname.' '.$lastname.' Testimonial - Click the link to view this testimonial<br>Written '.$datemade.'</p>';
}
mysqli_close($db_conx);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
div#pagination_controls{font-size:21px;}
div#pagination_controls > a{ color:#06F; }
div#pagination_controls > a:visited{ color:#06F; }
</style>
</head>
<body>
<div>
<h2><?php echo $textline1; ?> Paged</h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>