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.
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 have a function in php I use it for paging it is like this :
$query = "SELECT id,
FROM table
ORDER BY id ASC
LIMIT $offset,5";
this work fine but what I want is to get the page that contain id number let say 10 and with it the other 4 rows, I want it to return something like this:
7,8,9,10,11,12 -> if I give it id number 10.
25,26,27,28,29 -> if I give it id number 26 and so on.
like it would return the 5 rows but I want to know how to set the offset that will get me
the page that have the 5 rows with the specified id included.
what should I do like adding where clause or something to get what I want!
Notice that the IDs in your table won't be consecutive if you delete some rows. The code below should work in such conditions:
$result = mysql_query('select count(*) from table where id < ' . $someId);
$offset = mysql_result($result, 0, 0);
$result = mysql_query('select * from table order by id limit ' . max($offset - 2, 0) . ',5');
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Try something like this
//but for pagination to work $page should be $page*$limit, so new rows will come to your page
$limit = 5;
$start = ($page*limit) -2; // for normal pagination
$start = $page -2; // for your case, if you want ids around the $page value - in this case for id = 10 you will get 8 9 10 11 12
if ($start < 0) $start = 0; // for first page not to try and get negative values
$query = "SELECT id,
FROM rowa
ORDER BY id ASC
LIMIT $start,$limit";
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");
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.