I have a website that I'm building on my localhost using the MVC design pattern. I have button on click that will display all the genres in TheMovieDatabase which I got using the TheMovieDatabaseAPI. On click of a genre I get data for Page 1 with 20 results. But, I couldn't figure out how to request the results for page 2. These requests are made using PHP.
I am assuming you are taking about pagination using, I am also assuming you are using mySQL as database, I am not sure which framework you are using,
Here is a function i use, you can build around this
function get_movie($page = 1){
global $database_connection;
$start = 0; //Don't modify this
$limit = 10; //set this to 20 to display 20 movies per page
$start = ($page - 1)* $limit;
//get the movie from the table
$sql = "SELECT genre FROM movie_table LIMIT $start, $limit";
$result = mysqli_query($database_connection, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div>$row['genre']</div>";
}
$movie_rows = mysqli_num_rows (mysqli_query($database_connection ,"SELECT * FROM movie_table"));
$total = ceil($testimony_rows / $limit);
if (isset($page)){
echo "<div>";
echo "<ul class='pager'>";
if($page > 1) {
echo "<a href='?page=".($page - 1)."' style='float: left;' class=' w3-sand w3-btn w3-margin w3-round'>Previous</a>";
}
for($i = 1; $i <= $total; $i++) {
if($i == $page) { echo "<li class='active current'>".$i."</li>"; }
else { echo "<li><a href='?page=".$i."'>".$i."</a></li>"; }
}
if($page != $total) {
echo "<a href='?page=".($page + 1)."' class='w3-btn w3-margin w3-sand w3-round'>Next</a>";
}
echo "</ul></div>";
}
}
you can use limit and offset to get the result for page 2.
Example :- if you are using query builder to get the results
$limit = 20;
$offset = 21;
$queryBuilder->select('d')
->from(<table name>, 'd')
->setMaxResults($limit)
->setFirstResult($offset)
->setParameter('limit', $limit)
->setParameter('offset', $offset);
If you are using raw query :
SELECT * FROM table LIMIT 20 OFFSET 21
Else you can use paginator too
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $pageSize);
// now get one page's items:
$paginator
->getQuery()
->setFirstResult($pageSize * ($currentPage-1)) // set the offset
->setMaxResults($pageSize); // set the limit
foreach ($paginator as $pageItem) {
echo "<li>" . $pageItem->getName() . "</li>";
}
Related
I've been trying for hours to implement a pagination for a blog that I am working on, but I just can't find it to work. In the URL, it gives me (myurl).php?pageno=
Without the page number requested.
This is my page to handle the database request:
<?php
require_once("db-connect.php");
$offset = 0;
$page_result = 5;
if($_GET['pageno'])
{
$page_value = $_GET['pageno'];
if($page_value > 1)
{
$offset = ($page_value - 1) * $page_result;
}
}
$results = mysqli_query($connection, "SELECT * FROM blog where $condition ORDER BY date DESC LIMIT $offset, $page_result")
or die(mysqli_error('No Records Found'));
?>
This is my blog page code:
<?php
if (mysqli_num_rows($results) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($results)) {
echo "<li class='background-white'><div class='column large-4'><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>"."<img src='http://tmggeotech.com/img/blog/".$row['thumbnail']."' alt='".$row['thumbalt']."'/>"."</a></div>"."<div class='column large-8 article-data'>"."<h4><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>".$row["arttitle"]."</a></h4>"."<small class='text-black2'>Publicado el <span class='text-orange2'>".date('m/d/Y', strtotime($row['date']))."</span> | "."CategorÃa: <span class='text-orange2'>".$row["category"]."</span></small>"."<p>".$row["excerpt"]."</p>"."</div>"."</li>";
} }else {
echo "0 results";
}
$pagecount = 50; // Total number of rows
$num = $pagecount / $page_result;
if($_GET['pageno'] > 1) {
echo "Prev";
}
for($i = 1 ; $i <= $num ; $i++) {
echo "".$i."";
}
if($num != 1) {
echo "Next";
}
?>
So my question is:
Is it there something I am missing here to make it work?
Thanks to #ccKep for point out some clues on how to get what I needed. I just made it work.
In page to handle the database request, I added a second request but without LIMIT, so that I could use num_rows with it:
<?php
require_once("db-connect.php");
$offset = 0;
$page_result = 5;
if($_GET['pageno'])
{
$page_value = $_GET['pageno'];
if($page_value > 1)
{
$offset = ($page_value - 1) * $page_result;
}
}
$results = mysqli_query($connection, "SELECT * FROM blog where $condition ORDER BY date DESC LIMIT $offset, $page_result")
or die(mysqli_error('No Records Found'));
$npages = mysqli_query($connection, "SELECT * FROM blog where $condition ORDER BY date DESC")
or die(mysqli_error('No Records Found'));
?>
Later, on my blog page I round up my posts to the next multiple of 5 number.
And also changed my last if statement so that the NEXT button disappears after getting the last page.
<?php
if (mysqli_num_rows($results) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($results)) {
echo "<li class='background-white'><div class='column large-4'><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>"."<img src='http://tmggeotech.com/img/blog/".$row['thumbnail']."' alt='".$row['thumbalt']."'/>"."</a></div>"."<div class='column large-8 article-data'>"."<h4><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>".$row["arttitle"]."</a></h4>"."<small class='text-black2'>Publicado el <span class='text-orange2'>".date('m/d/Y', strtotime($row['date']))."</span> | "."CategorÃa: <span class='text-orange2'>".$row["category"]."</span></small>"."<p>".$row["excerpt"]."</p>"."</div>"."</li>";
} }else {
echo "0 results";
}
$x = ceil($npages->num_rows/5) * 5;
$pagecount = $x; // Total number of rows
$num = $pagecount / $page_result;
if($_GET['pageno'] > 1) {
echo "<a href='noticias-perforacion-suelos-articulos-maquinas-blog.php?pageno=".($_GET["pageno"] - 1)."'>Prev</a>";
}
for($i = 1 ; $i <= $num ; $i++) {
echo "<a href='noticias-perforacion-suelos-articulos-maquinas-blog.php?pageno=".$i."'>".$i."</a>";
}
if($_GET['pageno'] == $num) {
echo "";
} else {
echo "<a href='noticias-perforacion-suelos-articulos-maquinas-blog.php?pageno=".($_GET["pageno"] + 1)."'>Next</a>";
}
?>
You might notice that I am not a very good coder, so if you find a less messy way to do this please let me know.
Cheers!
i create a php news system, but i have a problem:
<?php
include('config.php');
if( isset( $_GET["page"]) ) $PAGE=$_GET["page"]; else $PAGE=1;
$query1=mysql_query("select id, name, email , age from addd LIMIT ". (($PAGE * 5) - 5) .",5");
echo "<table><tr><td>Testo</td><td>Nome</td><td>Anni</td></tr>";
function truncate_string($str, $length) {
if (!(strlen($query2['name']) <= $length)) {
$query2['name'] = substr($query2['name'], 0, strpos($query2['name'], ' ', $length)) . '...';
}
return $query2['name'];
}
while($query2=mysql_fetch_array($query1))
{
$number= $query2['name'];
echo "<tr><td>".substr($query2['name'], 0, 500)."...</td>";
echo "<td>".$query2['email']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td>".str_word_count($number)."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Mod</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."' onclick=\"return confirm('Sei sicuro di volerlo eliminare?');\");'>Canc</a></td><tr>";
echo "<td><a href='singletwo.php?id=".$query2['id']."');'>vedi</a></td<tr>";
}
?>
The pages follow this numbering: ?page=1, ?page=2 ecc.
Each page contains 5 news.
How do I create an automatic pagination system?
With Prev-Next, automatically detect possible next or previous pages?
I don't know how to do it.
Start by having the max length and total number of rows in variables:
<?php
include('config.php');
$max = 5;
$total = mysql_query("select count(*) from addd");
$PAGE = isset($_GET["page"]) ? $_GET["page"] : 1;
$query1 = mysql_query("select id, name, email , age from addd LIMIT " . (($PAGE * $max) - $max) . "," . $max);
That way, you can calculate how many pages you'll need.
The following code will give you a page list (Page 1, Page 2, Page 3 etc.):
for($i = 0; $i < ceil($total / $max); $i ++)
{
$p = $i + 1;
echo 'Page ' . $p . '';
}
If you'd rather have Previous and Next links, try this:
if($PAGE > 1)
echo '<a href="?page=' . ($PAGE - 1) . '>Previous</a>';
if(ceil($total / $max) > $PAGE)
echo '<a href="?page=' . ($PAGE + 1) . '>Next</a>';
What you could do is:
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = $currentPage*5;
$offset = $offset-5;
Now that you have these numbers, you can use them in your query:
$stmt = "SELECT
...
FROM news
LIMIT ".$offset.", ".$limit.";
This way you'll get the records you want. As far as the next and previous buttons go:
if ($currentPage > 1) {
// Show previous button
}
For the next button you'll need to do another query:
$stmt = "SELECT COUNT(*) as total FROM news";
$result = $pdo->fetch();
$totalRows = $result['total'];
if ($currentPage < round($totalRows/5)) {
// Show next button
}
I am trying to set up a jqgrid and I am having difficulty in constructing the controller that generates the json data to populate the grid. I am using codeigniter 2.0+ and I am not sure how to build the query for php in codeigniter.
I followed this guid under "Loading Data -> JSON Data" for the jqgrid. I also consulted codeigniter docs on data selection. The thing is I am not sure how to write the second query to sort and limit according to the jqgrid paramiters. Here is my controller.
public function applicantdata(){
$page = $this->input->get('page');// get the requested page
$limit = $this->input->get('rows');// get how many rows we want to have into the grid
$sidx = $this->input->get('sidx');// get index row - i.e. user click to sort
$sord = $this->input->get('sord');// get the direction
if(!$sidx){ $sidx =1; }
$this->db->select('*');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$query = $this->db->get();
$count = $query->num_rows();
$limit = 10;
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages; }
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
//NOT SURE HOW TO DO THIS IN CODEIGNITER ENVIRONMENT
//$SQL = "SELECT a.id, a.invdate, b.name, a.amount,a.tax,a.total,a.note FROM invheader a, clients b WHERE a.client_id=b.client_id ORDER BY $sidx $sord LIMIT $start , $limit";
//$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$result = $query->result_array();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
foreach ($result as $myrow){
$responce->rows[$i]['id']=$myrow['id'];
$responce->rows[$i]['cell']=array($myrow['id'],$myrow['firstname'],$myrow['lastname'],$myrow['amount'],$myrow['status']);
$i++;
}
echo json_encode($responce);
}
With the above code, the grid is populating and its is working to a greater extent. Only thing is the pagination stuff not working properly in that the data on page one shows when I move to page 2, 3, etc.
Her is the final working thing. For anyone who may need it.
public function applicantdata(){
$page = $this->input->get('page');// get the requested page
$limit = $this->input->get('rows');// get how many rows we want to have into the grid
$sidx = $this->input->get('sidx');// get index row - i.e. user click to sort
$sord = $this->input->get('sord');// get the direction
if(!$sidx){ $sidx =1; }
$this->db->select('firstname');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$query = $this->db->get();
$count = $query->num_rows();
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages; }
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$this->db->select('*');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$this->db->order_by("applicant.id", $sord);
$this->db->limit($limit, $start);
$query2 = $this->db->get();
$result = $query2->result_array();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
foreach ($result as $myrow){
$responce->rows[$i]['id']=$myrow['id'];
$responce->rows[$i]['cell']=array($myrow['id'],$myrow['firstname'],$myrow['lastname'],$myrow['amount'],$myrow['status']);
$i++;
}
echo json_encode($responce);
}
I am creating a page that lists celebrities on Twitter. The page displays 10 different results as it should for the first loop but it doesn't seem to update the $result to pull the next 10 values from the database (for the next set of pages etc).
<?php
// connect to the database
$con = mysql_connect("localhost","someuid","somepwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("celebrity_twitter", $con);
$result = mysql_query("SELECT * FROM celebrities");
// number of results to show per page
$per_page = 10;
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display data in table
echo "<table class='table table-striped'>";
echo "<tr> <th>Avatar</th> <th>Celebrity Name</th> </tr>";
// loop through results of database query, displaying them in the table
for($i = $start; $i < $end; $i++ && $row = mysql_fetch_array($result) )
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo "<td><img height='73' width='73' src=" . "http://api.twitter.com/1/users/profile_image?screen_name=" . $row['avatar'] . "&size=bigger></td>";
echo "<td><a href=" . $row['url'] . " target='_blank'>" . $row['uid'] . "</td></a>";
echo "</tr>";
}
// close table>
echo "</table>";
// display pagination
echo "<strong>Page: </strong>";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='index.php?page=$i'>$i</a> ";
}
?>
I'm using this at the moment and it's working perfectly fine for me, I hope it works for you too : PHP Pagination
You are not positioning yourself in the database, you always read the first elements:
// loop through results of database query, displaying them in the table
for($i = $start; $i < $end; $i++ && $row = mysql_fetch_array($result) )
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
The proper way of doing this would be using the LIMIT clause of MySQL, with a special clause for recovering the true number of records
SELECT SQL_CALC_FOUND_ROWS * FROM celebrities LIMIT $start, $resultsperpage;
SELECT FOUND_ROWS(); // This is number of celebrities
This means that you need to calculate $start "before" running the query, i.e., "before" you know whether $start is a valid start at all. So you have to prepare for the case in which no rows are returned.
A quick alternative, which is pretty wasteful, is to retrieve everything and display only wanted rows:
// loop through results of database query, displaying them in the table
for ($i = 0; $i < $total_results; $i++)
{
$row = mysql_fetch_array($result);
if ($i < $start) continue;
if ($i == $end) break;
LIMIT implementation
mysql_select_db("celebrity_twitter", $con);
// number of results to show per page
$per_page = 10;
// We REALLY ought to move on to PDO: mysql_* will be deprecated sooner or later
$query = mysql_query('SELECT SQL_CALC_FOUND_ROWS * FROM celebrities');
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = (int)$_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0)
$start = ($show_page -1) * $per_page;
else
$start = 0;
$query .= " LIMIT $start, $per_page;";
$paged = True;
}
else
{
$paged = False;
// The query having no LIMIT, it will retrieve everything
// if (!$paged), later we will display a link "Show Paged".
}
// Now run the query
$result = mysql_query($query);
// Also fetch REAL number of rows in table {{{
$exec = mysql_query("SELECT FOUND_ROWS() AS results;");
$tuple = mysql_fetch_assoc($exec);
$results= $tuple['results'];
mysql_free_result($exec);
unset($exec, $tuple);
// }}}
// If paging, calculate page number. Later, if ($paged), we'll display the pager.
if ($paged)
{
$maxpages = ceil($results / $per_page);
if ($page > $maxpages)
$page = $maxpages+1; // We fetch nothing.
else
$page = floor($start / $per_page)+1;
}
// display data in table. It is best to calculate $html first
// and then output it all together at end if no error.
$html = "<table class='table table-striped'>";
$html .= "<tr> <th>Avatar</th> <th>Celebrity Name</th> </tr>";
// loop through results of database query, displaying them in the table
// Here, we get all and only good results, so we need not check anything
while($row = mysql_fetch_array($result))
{
// echo out the contents of each row into a table
$html .= "<tr>";
}
I have a small problem with my PHP pagination, I have 6 records and I display 2 at a time, when I click on next and it displays from 2 to 4 records, that works fine, But to display from 4 to 6 records, that does not work. I am not sure what im doing wrong. Anyone have any ideas ? the problem is to do with the calculation for the Next records to be displayed
<?php
$per_page = 2;
$start = $_GET['start'];
$query = mysql_query("SELECT * FROM Directory");
$record_count = mysql_num_rows($query);
$record_count = round($record_count / $per_page);
if(!$start) {
$start = 0;
}
$query = mysql_query("SELECT * FROM Directory LIMIT $start,$per_page") or die(mysql_error());
$row = mysql_num_rows($query);
// Output Records here
// Setup next and previous button variables
$prev = $start - $per_page;
$next = $start + $per_page;
echo '<p> <h4>';
if($prev < 0) {
echo 'Previous';
} else {
echo '<a href="directory.php?start='.$prev.'>Previous</a>';
}
echo ' ' . $start . ' of ' . $record_count;
if($next < $record_count) {
echo ' <a href="directory.php?start='.$next.'>Next</a>';
} else {
echo ' Next';
}
echo '</h4> </p>';
?>
It looks like it's a formatting issue. When I look at your source for the URL http://gebsbo.limewebs.com/directory/directory.php?start=1 I see:
<br /><p> <h4>Previous 1 of 4 <a href="directory.php?start=3>Next</a></h4> </p> </body>
It looks like you're missing a quote on the href attribute.
In your code, you want:
echo 'Previous';
and
echo ' Next';
use this code for calculating :
$num = 10; // number of items on page
$p = $_GET['page']; // the var that comes from url (for ex: htttp://..../xxx.php?page=3)
$r = mysql_query(" select * from your_table ");
$posts=mysql_num_rows($r); // total posts
$total=(($posts-1)/$num)+1; // toatal pages
$total=intval($total);
$p=intval($p);
if(empty($p) or $p<0 or !isset($p)) $p=1;
if($p>$total) $p=$total;
$start=$p*$num-$num;
// here print the html for pagination (for ex: htttp://...../xxx.php?page=1 .. 2 ...3 .... and so on ...) you can make a for() here
$r = mysql_query(" select * from your_table limit ".$start.", ".$num);
while (....) {
.....
}