i wrote a query to get my posts with DESC order as you see its limitet to show 10 posts per page
but how i can find the post with "pid = 18" in what page?
TABLE:
pid, posterid, content
1 , 26 , blabla
2 , 8 , sec balnla
3 , 9 , lollll
4 , 26 , orddddd
5 , 10 , sssssdsd
...
PHP:
function getComments($poster){
$sql = "SELECT * FROM table WHERE posterid = $poster"
$smt = $db->query($sql);
$total = $smt->rowCount();
$result = $db->prepare($sql . " ORDER BY pid DESC $limit");
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$Comments[] = $row;
}
return [
'comments' => $Comments,
'total' => $total
];
}
NEEDED FUNCTION:
$poster = 26;
$pid = 18;
$posttperpage = 10;
public function getPostPage($pid, $poster, $posttperpage)
{
$page = '';
$totlaPosts = getComments($poster)['total']; //70
$pages = $totlaPosts / $posttperpage; //7
for($i=0, $i<$totlaPosts, $i--)
{
// ?????
// i confuzed no idead what can i do :(
}
return $page; //it must be 2
}
Since pid is not necessarily consistent (you might have deleted some rows) you should have another query.
$stmt = $db->prepare("SELECT COUNT(1) FROM table WHERE pid <= ? AND poster = ?");
$stmt->execute([$pid, $poster]);
$count = $stmt->fetchColumn();
echo ceil($count / $posttperpage);
If you're looking to determine what page a post is on:
$k = 1;
for($i=0, $i<$pid; $i += $posttperpage){
$page = $k;
$k +=1;
}
//after loop $page now contains what page the post is on.
Is this what you're looking for?
In your LIMIT 0,10 you have a range of 10 items per page, right? If you want to keep track of which page you are viewing you need a variable that behaves like this:
$range = 10;
$currentPage = 2;
$offset = $range * ($currentPage - 1);
Inside your query you can change that 0 to $offset and there you have it, if you find your result in with this query it means your pid is in page 2, you can also increase the $currentPage by 1 if you can't find your result and so on.
This algo is simple,
You need to know the total of row, the position of your specific post and number of post per page.
And you do like this :
floor(position_of_you_post / number_total_of_post * number_of_post_per_page)
so if you have 100 post with 10 post per page and your post is the number 51, you can do :
51 /100 * 10 = 5.1
so the post is on the page 5
Related
I created php script following the tutorial, but it has a mistake. It displays in the last page information which is in the previous page - it's because $perpage. How can I display only data which wasn't display yet.
EXAMPLE - If I set $perpage to 3 and I have 7 records (named 1,2,3,4,5,6,7) on page one is 1,2,3 on page two is 4,5,6 and on the last page is 5,6,7 (I want to display only record 7)
$query = mysql_query("SELECT ID FROM clanek");
$count = mysql_num_rows($query);
$perpage = 3; // řádků na stránku
$pages_count = ceil($count / $perpage); //celkem stránek zaokrohleno
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$is_first = $page == 1; //první stránka
$is_last = $page == $pages_count;
$prev = max(1, $page - 1);
$next = min($pages_count , $page + 1); /
$data = mysql_query("SELECT DATE_FORMAT(datum_pridani_c,'%d.%m.%Y %H:%i:%s')as datumcas,nazev,kratky_popis,ID FROM clanek ORDER BY datum_pridani_c DESC LIMIT ".($page - 1).", ".$perpage); /
while ($zaznam = mysql_fetch_array($data)) {
//some info her
}
if($pages_count>0) {
if(!$is_first) {
echo '<a class="predchozistranka" href="index.php?page='.$prev.'">Předchozí</a>';
}
echo '<span class="stranka">Stránka '.$page.' / '.$pages_count.'</span>';
if(!$is_last) {
echo '<a class="dalsistranka" href="index.php?page='.$next.'">Další</a>';
}
}
$data = mysql_query("SELECT DATE_FORMAT(datum_pridani_c,'%d.%m.%Y %H:%i:%s')as datumcas,nazev,kratky_popis,ID FROM clanek ORDER BY datum_pridani_c DESC LIMIT ".($page - 1).", ".$perpage);
It has been a while since I have used MySQL but I fired up my Workbench just now and I see that the syntax for LIMIT is LIMIT offset,rowcount. The doc says so too http://dev.mysql.com/doc/refman/5.0/en/select.html
For your query to work then, instead of ($page - 1), $perpage, it should be ($page - 1)*$perpage, $perpage
$query = mysql_query("SELECT ID FROM clanek");
$count = mysql_num_rows($query);
Irrelevant but the above code is highly inefficient for getting the total number of rows. It would be better if you use SELECT count(id) FROM clanek
So like the title suggests, I am trying to retrieve records from multiple tables.
I have the following tables : ads1 , ads2 , ads3 ,.... each tables containes 1 or more records with auto_increment id and names of people under the column named names.
Let's say I have 10 records in each tables, and I have a pagination script that shows 5 records per page, that means 2 pages for each table, so I will have pages 1,2,3,4,5,6.
My algorithm doesn't do it correctly, on my first page it shows 5 record from the first table, 5 records from the second table , 5 records from the third table and so on... but I only want 5 records to be shown per page , not 5 from each table that I have, I want them to be shown correctly on pages 1 and 2 records from ads1 , on pages 3 and 4 records from ads2 and so on, hope you get the idea.
Can you please help me ?
here is my alogorithm :
for ($i=1;$i<=$kay;$i++)
{
$counter = 0;
$tablenow = 'ads'.$i;
$result = mysql_query("SELECT id FROM ".$tablenow." ");
$counter = $counter + mysql_num_rows($result);
$x=ceil($counter / $per_page);
$page = (isset ($_GET['page']) AND (int)$_GET['page'] > 0 AND (int)$_GET['page'] <= $x) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$sql = mysql_query("SELECT * FROM ".$tablenow." ORDER BY id DESC LIMIT
$start,$per_page ")or die(mysql_error());
while ($sqlg=mysql_fetch_assoc($sql))
{
// this is where I show the records.
}
}
PS: For only one table , the algorithm works exactly as it should, but when I have 2 or more tables it stops working correctly.
Here's one way to do it:
$count_tables = 10;
$query = '';
for ($table_no = 1; $table_no <= $count_tables; $table_no++ ) {
$query .= "SELECT * FROM ads" . $table_no . " UNION ";
}
// Remove trailing UNION
$query = preg_replace( '/ UNION \Z/', '', $query );
$result = mysql_query("SELECT id FROM ".$tablenow." ");
$total_rows = mysql_num_rows($result);
$max_page = ceil( $total_rows / $per_page );
// Fetch rows for the page
$query_for_page .= $query . " ORDER BY id DESC LIMIT $start, $per_page";
$page = ( isset ($_GET['page'])
AND (int)$_GET['page'] > 0
AND (int)$_GET['page'] <= $max_page ) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$page_results = mysql_query( $query_for_page ) or die( mysql_error() );
while ( $row = mysql_fetch_assoc( $page_results ) ) {
// this is where I show the records.
}
Hope this helps.
You have to execute only one query, which will be an UNION of the results of all desired tables. If you execute SELECTs in each table individually, you cannot track the total results in an accurate way.
I am displaying some records from the database. Currently I am displaying the top twenty records but I want to show all records with twenty records per page.
How will I use the paging in php to display all records?'
Any Idea about this?
Something like this might work:
$posts_per_page = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
$query = sprintf("SELECT * FROM <table> LIMIT %d, %d",
$page * $post_per_page,
$posts_per_page);
$result = mysql_query($query);
The above query will select 10 records with a offset based on the current page.
You will also have to get the total number of pages based on the $posts_per_page:
$query = "SELECT COUNT(*) c FROM <table>";
You will have to keep track of the total number of posts divided with $posts_per_page and also the current page, then you can display a prev and next link:
if ($current_page > 0) {
echo '<a href="index.php?page=' . ($current_page - 1) . '>prev</a>';
}
if ($current_page < $max_pages - 1) {
echo '<a href="index.php?page=' . ($current_page + 1) . '>next</a>';
}
The basic idea is to send a page variable, for example $page, to your script and then customize your MySQL query to retrieve only that page's results.
Here is an example so you can see what I mean:
$page = $_GET['page'];
$resultsPerPage = 20;
$start = ($page - 1) * $resultsPerPage;
$query = "SELECT `results` FROM `table` WHERE ... ORDER BY `date` LIMIT $start, $resultsPerPage"
You can see how if $page = 1, then $start = 0 and this query will retrieve the 20 results, offset at 0. For $page = 2, $start = 20 so the query will retrieve the results from 20 - 40, which should show on the second page.
This is assuming your first page is 1. If you want the first page to be 0, then you need to change $start:
$start = $page * $resultsPerPage;
I have a MySQL query
SELECT * FROM 'redirect'
WHERE 'user_id'= \''.$_SESSION['user_id'].' \'
ORDER BY 'timestamp'`
I want to paginate 10 results per page. How Can I do it?
Here is a nice starting point:
<?php
// insert your mysql connection code here
$perPage = 10;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
$query = "SELECT COUNT(*) as total FROM redirect
WHERE user_id = '".$_SESSION['user_id']."'";
$r = mysql_fetch_assoc(mysql_query($query));
$totalPages = ceil($r['total'] / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page )
? "<a href='index.php?page=$i'>Page $i</a> "
: "$page ";
}
$r = mysql_query($query);
$query = "SELECT * FROM 'redirect'
WHERE 'user_id'= \''.$_SESSION['user_id'].' \'
ORDER BY 'timestamp' LIMIT $startAt, $perPage";
$r = mysql_query($query);
// display results here the way you want
echo $links; // show links to other pages
Use LIMIT.
SELECT *
FROM redirect
WHERE user_id = '35251'
ORDER BY timestamp
LIMIT 40, 10
40 is how many records to skip, 10 is how many to display.
There are also a few problems with your PHP. You use backticks (not single quotes) to surround table and column names. And you shouldn't use string concatenation to build your query.
Here is my code
which contains next and Previous button
<?php
$limit = 3; //set Number of entries to show in a page.
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else { $page=1;
}
//determine the sql LIMIT starting number for the results on the displaying page
$page_index = ($page-1) * $limit; // 0
$All_Users=mysqli_query($con,"select * from users limit $page_index, $limit");
while($row=mysqli_fetch_array($All_Users))
{
//show data in table or where you want..
}
$all_data=mysqli_query($con,"select count(*) from users");
$user_count = mysqli_fetch_row($all_data); // say total count 9
$total_records = $user_count[0]; //9
$total_pages = ceil($total_records / $limit); // 9/3= 3
if($page >= 2){
echo "<a href='blog.php?page=".($page-1)."' class='btn
customBtn2'>Previous</a>";
}
if($page<$total_pages) {
echo "<a href='blog.php?page=".($page+1)."' class='btn customBtn2'>NEXT</a>";
}
?>
Use the LIMIT clausule of the query to limit the amount of results you retrieve from the database.
See: http://dev.mysql.com/doc/refman/5.1/en/select.html
i have a table where a Collection has many Entities and an Entity has and belongs to many colections..now for a particular collection there are many entities..how can i paginate those entities belonging to a particular collection..
my find query says..,
$this->Collection->find('first', array('condition'=>array('uid'=>$uid)),
'contains(array('Entity')));
now how to paginate the result of entities..
In your controller action
$this->paginate=array('Entity' => array(
'conditions' => "Entity.collection_id=$id",
'fields' => array('Entity.*')
)
);
$this->set('entities', $this->paginate($this->Collection->Entity));
I'm assuming here that you're using an SQL database.
Now i haven't tested the code, but i think it should work.
// First query to get some info.
$testquery = mysql_query("SELECT * FROM `table` WHERE `entity` = 'something'");
if(!$testquery) die(mysql_error());
$total_items = mysql_num_rows($testquery); // Count the total number of entity's that match the criteria.
$limit = 10; // Maximun number of entity's on page.
$page = $_GET['page'];
//calcuate total pages
$total_pages = ceil($total_items / $limit); // ceil is used to round up fractions to the next int
$set_limit = $page * $limit - ($limit);
$query2 = mysql_query("SELECT * FROM `table` WHERE `entity` = 'something' LIMIT $set_limit, $limit");
if(!$query2) die(mysql_error());
//show data matching query:
while($code = mysql_fetch_object($query2)) {
echo("item: ".$code->title."<BR>");
}
// This displays the "previous page" link if there is a previous page.
$prev_page = $page - 1;
if($prev_page >= 1) {
echo("<a href=yourpagename.php?page=$prev_page>Previous</a>");
}
//Display middle pages:
$mid_page = 1;
while ($total_pages >= $mid_page) {
if ($page == $midpage){
echo ("<b>$mid_page</b> | ");
}
else {
echo (" <a href=yourpagename.php?page=$mid_page> $mid_page </a> | ");
$midpage++;
}
}
// This page will display a "next page" link if there is one.
$next_page = $page + 1;
if($next_page <= $total_pages) {
echo("<a href=yourpagename.php?page=$next_page>Next</a>");
}