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!
Related
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>";
}
I have the following code:
$max = 4;
$page = isset($_GET['page']) ? ($_GET['page']) : '1';
$init = $page - 1;
$init= $max * $init;
$strCount = "SELECT COUNT(*) AS 'total_mytable' FROM mytable";
$varstrCount = $crud->viewdatas($strCount);
$total = 0;
if(count($varstrCount)){
foreach ($varstrCount as $row) {
$total = $row["total_mytable"];
}
}
$result = "SELECT * FROM mytable ORDER BY id_mytable LIMIT $init,$max";
$varresult = $crud->viewdatas($result);
content of page:
<?php
if(count($varresult)){
foreach ($varresult as $res) {
?>
<h5><?php echo $res['title'] ?></h5>
<?php
}
}
?>
<?php
$max_links = 10;
$previous = $page - 1;
$next = $page + 1;
$pgs = ceil($total / $max);
if($pgs > 1 ){
if($previous > 0){
echo "<li><a href='".BASE_URL."/category/$previous' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>";
} else{
}
for($i=$page-$max_links; $i <= $pgs-1; $i++) {
if ($i <= 0){
}else{
if($i != $page{
if($i == $pgs){ //if end insert 3 dots
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li> ...";
}else{
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li>";
}
} else{
if($i == $pgs){ //if end insert 3 dots
echo "<li>".$i."</li> ...";
}else{
echo "<li>".$i."</li>";
}
}
}
}
if($next <= $pgs){
echo "<li><a href='".BASE_URL."/category/$next' aria-label='Next'><span aria-hidden='true'>»</span></a></li>";
}else{
}
}
?>
The result:
And I not understand the reason for the active number stay right off the paging menu
In the code I defined max-links for 10, but no show number 5 and if I define max links for 3 changes nothing , displays the same result as the image.
Thanks for any help
echo "<li>".$i."</li>";
on the above line add up a href, seems like you have css formatting for li>a because of which you are not getting the required formatting on only li. so for getting better formatting for all paging links current, prev, next. you need to add up a tags.
echo "<li><a>".$i."</a></li>"; //in your else part
Pagination problem in search result
I am trying to paginate the search results, Here is the code that i'm using to look up for the search queries from user's form. I am getting search results paginated, but when i click 2 nd page of results it shows undefined index for those item posted...While gone through tutorials i have seen to use $_GET instead of $_POST ,after doing that chane also no improvement in results
As i am new to this php code, can you guys help or guide me in the right direction?
/////////////test.php//////////////////
mysqli_report(MYSQLI_REPORT_ERROR);
// number of results to show per page
$per_page = 2;
// figure out the total pages in the database
if ($result = $mysqli->query("SELECT * FROM bridegroom where Gender like '%$Name%' and Castest like'%$caste%' and Location like '%$location%' order by AGE"))
{
if ($result->num_rows != 0){
$total_results = $result->num_rows;
// ceil() returns the next highest integer value by rounding up value if necessary
$total_pages = ceil($total_results / $per_page);
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p> <b>View search results:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='test.php?page=$i'>$i</a> ";
}
}
echo "</p>";
// display data in table
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// find specific row
$result->data_seek($i);
$row = $result->fetch_row();
// echo out the contents of each row into a table
echo ("Name:$row[1]<br><span class=\"old\"> Age:$row[4]</span><br><span class=\"sold\">Caste:$row[5]</span><br><span class=\"old\">Location:</span><span class=\"sold\">$row[6]</span><br><br>");
}
// close table>
}
else
{
echo "No results to display!";
}
}
// error with the query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
// display pagination
echo "<p> <b>Your search results:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='test.php?page=$i'>$i</a> ";
}
}
echo "</p>";
?>
I have the following mysql query and I have added pagination from here:
http://www.tonymarston.net/php-mysql/pagination.html
$DBQuery3 = mysqli_query($dblink, "SELECT * FROM images WHERE project_id = '$FormProjectID'");
if (mysqli_num_rows($DBQuery3) < 1) {
$ProjectContent = '
<p>This project is empty. Upload some files to get started.</p>
';
} else {
//if no page number is set, start at page 1
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
//This code will count how many rows will satisfy the current query.
$DBQuery3b = mysqli_query($dblink, "SELECT count(*) FROM images WHERE project_id = '$FormProjectID'");
$query_data = mysqli_fetch_row($dblink, $DBQuery3b);
$numrows = $query_data[0];
//This code uses the values in $rows_per_page and $numrows in order to identify the number of the last page.
$rows_per_page = 2;
$lastpage = ceil($numrows/$rows_per_page);
//This code checks that the value of $pageno is an integer between 1 and $lastpage.
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
//This code will construct the LIMIT clause for the sql SELECT statement.
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$DBQuery3c = "SELECT * FROM images WHERE project_id = $FormProjectID $limit";
$DBQuery3d = mysqli_query($dblink, $DBQuery3c);
//set this variable to empty and so we can latwe loop and keep adding images to it
$ProjectContent ='';
while($row = mysqli_fetch_array($DBQuery3d)) {
$DBImageID = $row['image_id'];
$DBProjectID = $row['project_id'];
$DBImageName = $row['image_name'];
$DBImageDescription = $row['image_description'];
$DBDateCreated = $row['date_created'];
$DBLinkToFile = $row['link_to_file'];
$DBLinkToThumb = $row['link_to_thumbnail'];
$DBGivenName = $row['given_name'];
//if the image was given a name by the user, display it
//otherwise display the generated name
if (strlen($DBGivenName) > 1) {
$FileName = $DBGivenName;
} else {
$FileName = $DBImageName;
}
$ProjectContent .= '
<img src="uploads/'.$DBLinkToThumb.'" width="150px" height="150px" alt="'.$FileName.'" title="'.$FileName.'"/>
';
//Finally we must construct the hyperlinks which will allow the user to select other pages. We will start with the links for any previous pages.
if ($pageno == 1) {
$FirstPrev = " FIRST PREV ";
} else {
$First = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=1'>FIRST</a> ";
$prevpage = $pageno-1;
$Prev = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$prevpage'>PREV</a> ";
}
//Next we inform the user of his current position in the sequence of available pages.
$PageNumb = " ( Page $pageno of $lastpage ) ";
//This code will provide the links for any following pages.
if ($pageno == $lastpage) {
$NextLast = " NEXT LAST ";
} else {
$nextpage = $pageno+1;
$Next = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$nextpage'>NEXT</a> ";
$Last = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$lastpage'>LAST</a> ";
}
}
}
Then in my html I have:
<div id="projectview">
<?php echo $ProjectContent; ?>
<?php echo $FirstPrev; ?>
<?php echo $First; ?>
<?php echo $Prev; ?>
<?php echo $PageNumb; ?>
<?php echo $NextLast; ?>
<?php echo $Next; ?>
<?php echo $Last; ?>
<div class="clear-div"></div>
</div>
This is outputing for example in this case 2 images, but the pagination links look like this:
FIRST PREV ( Page 1 of 0 ) NEXT LAST
Clicking on the links is not cycling through any other images, it still shows the same 2 images.
I can't figure out what I have done wrong here. I don't understand why it says "1 of 0" when clearly there should be more results.
I need to loop through a recordset (PHP + MySQL), grouping each 2 records in a list item
My actual code (semplified) is this:
<?php
// how many total records do I have?
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);
$mCount = $row_rsMediaCount['med_count']; // total records
$mPages = ceil($mCount / 2); // max LIs to create
$mIndex = 0; // useful initialization for LIMIT, see below
if ($mCount > 0) { // let's show markup only if there's some record!
?>
<ul>
<?php for ($mPage = 1; $mPage <= $mPages; $mPage++) { // create the LIs ?>
<li>
<?php
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
do { ?>
<div><?php echo $row_rsMedia['med_id']; ?></div>
<?php } while ($row_rsMedia = mysql_fetch_assoc($rsMedia));
$mIndex += 2; // increment the LIMIT by 2 steps ?>
</li>
<?php } ?>
</ul>
<?php } ?>
The output is sort like this:
<ul>
<li>
<div>1</div>
<div>2</div>
</li>
<li>
<div>3</div>
<div>4</div>
</li>
<li>
<div>5</div>
</li>
</ul>
Everything works, but is there a more elegant or efficient solution?
Thanks in advance
Do only one query and group the results within the loop. Use the modulo operator %:
$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
if (mysql_num_rows($rsMedia) > 0) { // check if there is at least one result
echo '<ul>';
$index = 0;
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)) {
if ($index % 2 == 0) echo '<li>'; // open <li> bevore even result
echo '<div>'.$row_rsMedia['med_id'].'</div>';
if ($index % 2 == 1) echo '</li>'; // close <li> after odd result
$index++;
}
if ($index % 2 == 1) echo '</li>'; // close <li> if odd result count
echo '</ul>';
}
(just written, not testet)
I would try to run fewer queries.
$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$count = 0;
echo '<ul>';
while($row = mysql_fetch_assoc($rsMedia))
{
//check divisibility to know when to show li
if ($count % 2 == 0) {
echo '<li>';
}
echo '<div>' . $row['med_id'] . '</div>';
$count++;
if ($count % 2 == 0) {
echo '</li>';
}
}
if ($count % 2 == 1) echo '</li>';
echo '</ul>';
Ask query once without the LIMIT statement. Then do something like this:
$iteration=0;
echo '<li><ul>';
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)
{
echo '<div>'.$row_rsMedia['med_id'].'</div>';
$iteration++;
if ($iteration%2==0 && $iteration<$mCount)
echo '</ul><ul>'
}
echo '</ul><li>';
I would separate the HTML and PHP for ease of reading first. Also, I am not entirely convinced of the do...while loop that actually prints the result (what if the table was empty?).
Your code also contains two distinct ideas (generating the list and getting the page count), so I would break them into two separate functions. Makes code easier top read.
It may, therefore, look like this:
<ul>
<?php generateList(); ?>
</ul>
<?php
function getPageCount() {
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);
$mCount = $row_rsMediaCount['med_count'];
$mPages = ceil($mCount / 2);
}
function generateList()
$mIndex = 0;
$mPages = getPageCount();
if ($mCount > 0) {
for ($mPage = 1; $mPage <= $mPages; $mPage++) {
$result = "<li>" ;
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
while ((row_rsMedia = mysql_fetch_assoc($rsMedia)) != null) {
$result .= "<div>".$row_rsMedia['med_id']."</div>";
}
$mIndex += 2;
$result .= "</li>
}
echo $result;
}
?>
Hope it helps.