Paging in php displaying data over multiple pages - php

Hi I am trying to display my users data over pages
Here is my code:
//Run a query to select all the data from the users table
$perpage = 2;
$result = mysql_query("SELECT * FROM users LIMIT $perpage");
It does display this the only two per page but I was wondering how you get page numbers at the bottom that link to your data
here is my updated code
$result = mysql_query("SELECT * FROM users"); // Let's get the query
$nrResults=mysql_num_rows($result); // Count the results
if (($nrResults%$limit)<>0) {
$pmax=floor($nrResults/$limit)+1; // Divide to total result by the number of query
// to display per page($limit) and create a Max page
} else {
$pmax=floor($nrResults/$limit);
}
$result = mysql_query("SELECT * FROM users LIMIT 2 ".(($_GET["page"]-1)*$limit).", $limit");
// generate query considering limit
while($line = mysql_fetch_array( $result ))
{
?>
error
Parse error: syntax error, unexpected $end in E:\xampp\htdocs\Admin.php on line 98

In order to do this you also need to use the offset value in your SQL Statement, so it would be
SELECT * FROM users LIMIT $offset, $perpage
Example:
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
Then to get the links to put on the bottom of your page you would want to get a count of the total data, divide the total by the per page value to figure out how many pages you are going to have.
Then set your offset value based on what page the user clicked.
Hope that helps!
Update:
The unexpected end most likely means that you have an extra closing bracket } in your code which is causing the page to end and still has more code after it. Look through your code and match up the brackets to fix that. There are a few other issues in the code sample you pasted.
$result = mysql_query("SELECT * FROM users" ); //Note if you have a very large table you probably want to get the count instead of selecting all of the data...
$nrResults = mysql_num_rows( $result );
if( $_GET['page'] ) {
$page = $_GET['page']
} else {
$page = 1;
}
$per_page = 2;
$offset = ($page - 1) * $per_page; //So that page 1 starts at 0, page 2 starts at 2 etc.
$result = mysql_query("SELECT * FROM users LIMIT $offset,$per_page");
while( $line = mysql_fetch_array( $result ) )
{
//Do whatever you want with each row in here
}
Hope that helps
You can then use the nrResults number to figure out how many pages you are going to have... if you have 10 records and you are displaying 2 per page you would then have 5 pages, so you could print 5 links on the page each with the correct page # in the URL...

Use requests ! http://php.net/manual/en/reserved.variables.request.php
if (((isset($_GET['page'])) AND (is_int($_GET['page']))) {
$perpage = $_GET['page'];
}
$result = mysql_query("SELECT * FROM users LIMIT $perpage");
...
Link http://yourwebsite.com/userlistforexample.php?page=3
or
http://yourwebsite.com/userlistforexample.php?somethingishere=21&page=3

Related

PHP PDO pagination foreach

I'm trying to create a pagination for my PDO query. I cant figure it out. I've tried numerous google searches, but nothing that will work for me. [I probably didn't search hard enough. I'm not sure]
This is my code:
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
foreach ($nodes2 as $n1) {
echo "text";
}
I want to be able to limit 10 comments per page, and use $_GET['PAGE'] for the page.
Something that I tried
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
$page_of_pagination = 1;
$chunked = array_chunk($nodes2->get_items(), 10);
foreach ($chunked[$page_of_pagination] as $n1) {
echo "text";
}
If someone could help out, I appreciate it.
You need to limit the query that you are performing, getting all values from the database and then limiting the result to what you want is a bad design choice because it's highly inefficient.
You need to do this:
$page = (int)$_GET['PAGE']; // to prevent injection attacks or other issues
$rowsPerPage = 10;
$startLimit = ($page - 1) * $rowsPerPage; // -1 because you need to start from 0
$sql2 = "SELECT * FROM comments WHERE shown = '1' ORDER BY ID DESC LIMIT {$startLimit}, {$rowsPerPage}";
What LIMIT does:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants
More information here: http://dev.mysql.com/doc/refman/5.7/en/select.html
Then you can proceed getting the result and showing it.
Edit after comment:
To get all the pages for display you need to know how many pages are there so you need to do a count on that SELECT statement using the same filters, meaning:
SELECT COUNT(*) as count FROM comments WHERE shown = '1'
Store this count in a variable. To get the number of pages you divide the count by the number of rows per page you want to display and round up:
$totalNumberOfPages = ceil($count / $rowsPerPage);
and to display them:
foreach(range(1, $totalNumberOfPages) as $pageNumber) {
echo '' . $pageNumber . '';
}

PHP : get data from database

I am making a web service in php.
I want to have data from database in pagination manner.
eg : I should have 10 records based on event_id which i am passing in url along with page_number i.e 10 records on 1st page , another 10 records on 2nd page, and so on.
I am very new to web service.
<?php
http://localhost/Mobile%20Webservice/customAppEngine/faq.php?Faq_request={"faq_event_id":"302","page_number":"1"}
if(isset($_REQUEST["Faq_request"]) && trim($_REQUEST["Faq_request"]) != '') {
$faq_details_Request = $_REQUEST["Faq_request"];
// $page_number = 1;
$faqeventdetails_o = json_decode($faq_details_Request);
if( isset($faqeventdetails_o->faq_event_id))
{
// event_id
$event_id = $faqeventdetails_o->faq_event_id;
if(trim($event_id)==''){
die($msgobj->customFailMessage("Please provide Event Id"));
}
$userQuery="SELECT * FROM `faq` WHERE faq_event_id=$event_id";
$u=mysql_query($userQuery);
$number=mysql_num_rows($u);
/* if($number>0){
$query="DELETE FROM `agendaLikes` WHERE event_id=$event_id and user_id=$user_id
and agenda_id=$agenda_id";
mysql_query($query);
mysql_query("UPDATE agenda SET agendaLikes=agendaLikes-1 where agenda_id=$agenda_id");
$arr['isLike']=0;
}else{
mysql_query("INSERT INTO `agendaLikes`(agenda_id,user_id,event_id) VALUES($agenda_id,$user_id,$event_id)");
$arr['isLike']=1;
mysql_query("UPDATE agenda SET agendaLikes=agendaLikes+1 where agenda_id=$agenda_id");
}*/
$arr['status']=$msgobj->success;
echo json_encode($u);
}
else {
die($msgobj->customFailMessage($msgobj->missingparamater));
}
}
else {
die($msgobj->customFailMessage($msgobj->invalidparamater));
}
based on faq_event_id i should get data.
when i hit in url then nothing is displayed.
where m I lacking?
Thank You.
Use Offset And Limit in your sql query
let's say you want 10 records for each page then you need to pass page parameter.
so for Example
$page = 2; //parameter pass by get or post method
$limit = 10 //our limit to get data per page
$offset = $page*$limit; //calculate your offset
Then your sql will look like
$userQuery="SELECT * FROM faq WHERE faq_event_id=$event_id ORDER BY id LIMIT $limit OFFSET $offeset";
Hope this works for you.
You can use below code as well.
//Need to set this variable when you send request to get next 10 records, default value would be 1
$page=1;
$offset = 10;
$limit = ($page - 1) * 10;
$userQuery="$userQuery="SELECT * FROM faq WHERE faq_event_id=$event_id ORDER BY id";
if($page > 0)
$userQuery .= " limit $limit, $offset";

How to show 5 post each page with next & previous button feature?

I have a page named 'job.php', currently this page is showing all posted job. But now I want to show only 5 latest posts. And if anyone want to check the previous posts, they can click next button thus more 5 posts will be seen. There should be a previous button too.
Following is my code:
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC");
$num_row = mysql_num_rows($result1);
while($row1 = mysql_fetch_array($result1)){
$cat=$row1['Category'];
$title=$row1['Title'];
echo "Job field: $cat<br/> Title: $title<br/>";
}
N:B: It's not pagination. I don't want to show page numbers, just want to show next & previous button.
There are 100s of articles available on the Internet
Create Awesome PHP/MYSQL Pagination
PHP / MySQL select data and split on pages
If you want to do on your own:
Use LIMIT keywords in your query.
Pass the page and the multiplier to the LIMIT.
Some code
<?php
$limit = 5;
$start = (int)(($page - 1 ) * $limit);
$page = mysql_real_escape_string($_GET["page"]);
$query = "SELECT * FROM `table` LIMIT $start, {(int)$page + $limit}"
?>
There are two ways to achieve this.
1) In the query itself by using LIMIT
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC LIMIT 1, 5");
2 ) By using loop
$i = 0;
while($row1 = mysql_fetch_array($result1)){
if($i < 5) {
$cat=$row1['Category'];
$title=$row1['Title'];
echo "Job field: $cat<br/> Title: $title<br/>";
$i++;
}
}
You can pass the current value to URL and get it back by using $_GET..
You can use this query:
Select * from table_name ORDER BY ID DESC LIMIT 5;
I feel its better to use pagination. If you want dont want to show page nos, better hide it or just modify the code. If you planning to do it manually its a bit messy
You can use LIMIT in you mysql query:
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC LIMIT 0, 5");

PHP/SQL list order not displaying

A little bit of information
I am currently working on a project where I can display my work as projects.
In my database I have set it up so the number within list tells the PHP where it should be - according to the MYSQL Query.
In my project page I have created pagination so that if there are more than 5 rows, a new project list page is added to the pagination.
(My forward and back pagination is done by images linked)
I use Jquery Ajax POST to call new pages in.
The problem:
I used to set my PHP query to order by name (project name) but I created a new column list so that I could present them in a custom order - according to the digit that is in list
But ever since I changed it from name to list - the page only shows 5 records and no longer gives me my pagination options (when it should)
I know the problem is to do with the 2 queries within the pagination - could anyone tell me how to resolve this.
I have tried making the list column Char, Varchar and INT all have not helped! :(
The Code:
PHP Pagination:
<?
$get_stuff = mysql_query("SELECT * FROM `projects` WHERE `cat`='$arrc' ORDER BY `list` ASC")or die(mysql_error());
$getid = mysql_num_rows($get_stuff);
$r = mysql_fetch_row($get_stuff);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 5;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_POST['pid']) && is_numeric($_POST['pid'])) {
// cast var as int
$currentpage = (int) $_POST['pid'];
} else {
// default page num
$currentpage = 1;
} // end if
// if 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 first page...
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) * $rowsperpage;
// get the info from the db
$get_stuff2 = mysql_query("SELECT * FROM `projects` WHERE `cat`='$arrc' ORDER BY `list` ASC LIMIT $offset, $rowsperpage")or die(mysql_error());
while($projectz = mysql_fetch_array($get_stuff2)){
?>
<ul class="projex">
<li onClick="project('project','<? echo $projectz['id']; ?>','1','<? echo $currentpage; ?>')" class="onclick"> <? echo $projectz['name']; ?>
</ul>
<?
}
?>
I have not added my links code in as I know that is not the problem.
Your problem appears to be here:
<?
$get_stuff = mysql_query("SELECT * FROM `projects` WHERE `cat`='$arrc' ORDER BY `list` ASC")or die(mysql_error());
$getid = mysql_num_rows($get_stuff);
$r = mysql_fetch_row($get_stuff);
$numrows = $r[0];
You put the number of rows into $getid, then ignore that variable and put the first returned column from the results set into $numrows and use that. This means all the pagination calculations are based on the first column returned rather than the number of rows. I would guess that when ordered by name the first column was 7 and when ordered by list the first column is 5 or less.
My suggested fix would be to get the COUNT of rows in the SQL query, unless there is a pressing need for $getid that is not shown in your example:
<?php
$get_stuff = mysql_query("SELECT COUNT(*) FROM `projects` WHERE `cat`='$arrc'")or die(mysql_error());
$r = mysql_fetch_row($get_stuff);
$numrows = $r[0];

how to check current position in mysql

how can i check current number in mysql where....
my query is
$aid = 16;
$get_prev_photo = mysql_query("SELECT * FROM photos WHERE album_id='$aid' AND pic_id<'$picid' ORDER BY pic_id LIMIT 1");
$get_next_photo = mysql_query("SELECT * FROM photos WHERE album_id='$aid' AND pic_id>'$picid' ORDER BY pic_id LIMIT 1");
while i am getting current photo with following query
$photo = mysql_query("SELECT * FROM photos WHERE pic_id='$picid' LIMIT 1");
and getting total photos in album with following query
$photos = mysql_query("SELECT * FROM photos WHERE album_id='$aid'");
$total_photos = mysql_num_rows($photos);
now i want to check where i am and show it as Showing 1 of 20, showing 6 of 20 and so on...
now i want to check where i am actually...
i think you are referring to pagination, which can be achieved using LIMIT and OFFSET sql
decide the number of results you want per page, then select that many
create links like:
View the next 10
and dynamically change those every time
queries look ~like~
$offset=$_GET['view'];
SELECT * FROM table WHERE `condition`=true LIMIT 5 OFFSET $offset
this translates roughly as
select 5 from the table, starting at the 10th record
This is bad:
$photos = mysql_query("SELECT * FROM photos WHERE album_id='$aid'");
Because it grabs all the fields for the entire album of photos when all you really want is the count. Instead, get the total number of photos in the album like this:
$result = mysql_query("SELECT count(1) as total_photos FROM photos
WHERE album_id='$aid'");
if ($result === false) {
print mysql_error();
exit(1);
}
$row = mysql_fetch_object($result);
$total_photos = $row->total_photos;
mysql_free_result($result);
Now you have the count of the total number of photos in the album so that you can set up paging. Let's say as an example that the limit is set to 20 photos per page. So that means that you can list photos 1 - 20, 21 - 40, etc. Create a $page variable (from user input, default 1) that represents the page number you are on and $limit and $offset variables to plug into your query.
$limit = 20;
$page = $_POST['page'] || 1; // <-- or however you get user input
$offset = $limit * ($page - 1);
I'll leave the part where you code the list of pages up to you. Next query for the photos based on the variables you created.
$result = mysql_query("SELECT * FROM photos WHERE album_id='$aid'
ORDER BY pic_id LIMIT $limit OFFSET $offset");
if ($result === false) {
print mysql_error();
exit(1);
}
$photo_num = $offset;
while ($row = mysql_fetch_object($result)) {
$photo_num++;
$pic_id = $row->pic_id;
// get the rest of the variables and do stuff here
// like print the photo number for example
print "Showing photo $photo_num of $total_photos\n";
}
mysql_free_result($result);
I'll leave better error handing, doing something with the data, and the rest of the details up to you. But that is the basics. Also I did not check my code for errors so there might be some syntax problems above. To make a single photo per page just make $limit = 1.

Categories