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.
Related
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 . '';
}
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";
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");
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 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.