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";
Related
This question already has answers here:
PHP - MySQL query with Pagination
(4 answers)
Closed 9 years ago.
I want to display records from database using mysql_fetch_array. But the problem is i don't know how to fix the size to display in the page and move the rest of records to next page as there is too many records to be displayed.
Eg: Display first 10 rows(or records) in page1, then another 10 rows in another page?
Heres are my code:
$result=mysql_query("$selectKL UNION $selectKlang UNION $selectPJ UNION $selectSJ
ORDER BY restaurant_name LIMIT 6")
$searchQuery = search($budgetRange,$city,$category);
while($row = mysql_fetch_array($searchQuery))
{
echo"<tr>";
echo'<td>'.$row['restaurant_id'].'</b></td>';
echo'<td>'.$row['restaurant_name'].'</b></td>';
echo'<td>'.$row['category'].'</b></td>';
echo'<td>'.$row['budget'].'</b></td>';
echo'<td>'.$row['halal'].'</b></td>';
echo "</tr>";
}
There will be 30+ results to be displayed from my database but how do i display the first 10 result in 1st page, then another 10 result in next page and so on? I've already set the LIMIT to 10 in the query and yes it does only display 10 result, but i don't know how to store or pass the rest of result(is it possible?). Any help is appreciate... please?
Pagination can be tricky. You'll need to set up some parameters (probably query string parameters) to indicate enough information to know where to pick up your pagination, namely, either the number of results per page and the page number, or the number of the last result shown.
In your query, you can use LIMIT x,y where x is the starting row number and y is the number of rows to retrieve.
Pagination is a problem that's been solved many times over - that doesn't mean it's easy, but it means there's lots of help available. Try a quick search: https://encrypted.google.com/search?hl=en&q=php+mysql+pagination
/*
Place code to connect to your DB here.
*/
$tbl_name="xyz"; //your table name
// How many adjacent pages should be shown on each side?
$adjacents = 3;
/*
First get total number of rows in data table.
If you have a WHERE clause in your query, make sure you mirror it here.
*/
$query = "SELECT COUNT(*) as num FROM $tbl_name WHERE approved`=1 ";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages['num'];
/* Setup vars for query. */
$targetpage = "index.php"; //your file name (the name of this file)
$limit = 5; //how many items to show per page
$page = (!empty($_GET['page']) ? $_GET['page'] : null);
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
/* Get data. */
$sql = "SELECT * FROM $tbl_name WHERE `approved`=1 ORDER BY `id` DESC LIMIT $start, $limit ";
$result = mysql_query($sql);
/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
$lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1
include ('includes/pagination.php');
while($row = mysql_fetch_array($result))
{
//designate variables
echo 'Your content';
}
$pagination
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];
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
I use this code to get the informations about a certain id
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." ");
while($row = mysql_fetch_array($sql)){
$video_id = $row["id"];
$video_title = $row["title"];
}
Let's say the link of a page would be example.com/video.php?id=34
How can i get the next and previous $video_id and $video_title depending on the current id?
A problem is that i can't increase or decrease the value of the current id by 1 because the 35 or 33 may be deleted in the meanwhile...
How can i achieve this?
//edit
I have a very big problem: the previous link sends me to the right link but the next link always sends me to the last video added in the database.
If i go to the last or first videos added in the database i get an error because there are no more next and previous videos added.
Perhaps two more queries would work ...
select id,title from videos where id < $local_id order by id desc limit 1
select id,title from videos where id > $local_id order by id asc limit 1
You have to use select and limit to get that one row you want, i.e.,
SELECT * FROM `videos` WHERE `id` < " . $local_id . " ORDER BY `id` DESC LIMIT 1
Or use > and ORDER BYidASC for the next video, instead of the previous I showed above.
Here you go through
// entry per page
$rowsPerPage = 3;
// Set page number
if(isset($_GET['page']))
$pageNum = $_GET['page'];
else
$pageNum = 1;
Note: Following code is use to show/set next & previous page number.
Note: If the current page is homepage then default $pageNum is 1 and
if $pageNum is set as 2, it will work as
if($pageNum){
$PreviousPageNumber = $pageNum - 1;
$NextPageNumber = $pageNum + 1;
echo '<a href="?page='. $PreviousPageNumber .'>Previous Page</a>';
echo '<a href="?page='. $NextPageNumber .'>Next Page</a>";
}
Note: Following code is use to show record affected by page numbers
$GetPreviousRecord = ($pageNum - 1) * $rowsPerPage;
Note: The first, optional value of LIMIT is the start position. Note:
And the second required value is the number of rows to retrieve.
$query = "SELECT * FROM post WHERE LIMIT $GetPreviousRecord, $rowsPerPage";
$result = mysql_query($query);
And in last use the WHILE loop to get all records from database by using LIMIT.
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.