I want to be able to add a active class to a pagination so I know which page I am on but am unsure how to add it into the current code I have, below is what I currently have
$per_page=6;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
// Page will start from 0 and Multiple by Per Page
$start_from = ($page-1) * $per_page;
if ($result = $mysqli->query("SELECT * FROM TABLENAME ORDER BY COLUMNNAME ASC LIMIT $start_from, $per_page"))
// Count the total records
$total_records = mysqli_num_rows($result);
//Using ceil function to divide the total records on per page
$total_pages = ceil($total_records / $per_page);
//Going to first page
echo "<div class='btn-group' style='margin:0 auto;display:table;'>";
echo "<br><br><center><a href='view-all-customers.php?page=1' class='btn btn-primary float-button-
light' style='color:#FFFFFF;padding:6px 15px;'>".'First Page'."</a>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='view-all-customers.php?page=".$i."' class='btn btn-primary float-button-light'
style='color:#FFFFFF;padding:6px 15px;'>".$i."</a>";
};
// Going to last page
echo "<a href='view-all-customers.php?page=$total_pages' class='btn btn-primary float-button-light'
style='color:#FFFFFF;padding:6px 15px;'>".'Last Page'."</a></center>";
echo "</div>";
I have left out the data table rows as thought it's better to show the pagination coding more than showing the table tr and td rows outputting the data
//check page and add active class
for ($i=1; $i<=$total_pages; $i++) {
$isActive = '';
if($i == $page){
$isActive = 'active';
}
echo "<a href='view-all-customers.php?page=".$i."' class='".$isActive."btn btn-primary float-button-light' style='color:#FFFFFF;padding:6px 15px;'>".$i."</a>";
};
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 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 am using Bootstrap to display pagination on my pages but I have an issue. I want to use the bootstrap active class to show the current page but I don't know how to go about it.
When I add the active class (as shown in the code below), all the links become active. Please what do I do?
<?php
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 6;
$sql = "SELECT * FROM offers ORDER BY i.id ASC LIMIT $start_from, 6";
$sql2 = "SELECT COUNT(id) FROM offers";
$rs_result = $db-> query($sql2, array('id' => $_SESSION['id']));
$row = $rs_result->fetch();
$total_records = $row[0];
echo $total_records;
$total_pages = ceil($total_records / 6);
for ($i=1; $i<=$total_pages; $i++) {
;echo"
<ul class='pagination'>
<li class='active' ><a href='myoffer.php?page=$i' >$i</a></li>
</ul>
";
};
?>
You should add a condition that tells which page is currently being displayed (based on the value of the query string 'page', also you should put the echo <ul line before your loop:
echo "<ul class='pagination'>";
for ($i=1; $i<=$total_pages; $i++) {
if ($page == $i)
echo "<li class='active' >";
else
echo "<li>";
echo "<a href='myoffer.php?page=$i' >$i</a></li>";
};
echo "</ul>";
This is a copy of Aram Tchekrekjian's answer
($page == $i) ? "<li class='active' >" : "<li>";
Even better than that is to have the ternary operator inside of the <li>
tag and task it with echo class ="active" portion. So it would look like this
<li <?php ($page == $i) ? class="active" : false;?>>1</li>
I am building a product catalog, that I want to be determined depending on users device. ie., if windows device show particular products. I have my products listing absolutely fine, however when implementing pagination, I am stuck.
I want only 6 items to be listed per page, I have more results. However more results are showing on the first page. When I select to go next, the ID number changes, to show it is showing me the next result, but it continues to show the same page, so obviously I am missing/got confused somewhere with my code. I'd appreciate any advice:
$current_url = $_SERVER['REQUEST_URI'];
$current_url = substr($current_url, 1);
$results = mysqli_query($conn, "SELECT * FROM apps A INNER JOIN device D ON D.DeviceID = A.DeviceID WHERE D.DeviceName = '$os'");
$foundnum = mysqli_num_rows($results);
if ($foundnum==0){
echo "Sorry, there are currently no applications that are compatible with your device. Please try another option.";
} else {
echo "$foundnum applications are avaliable for '$os' devices:<p>";
$per_page = 6;
$start = $_GET['start'];
$max_pages = ceil($foundnum / $per_page);
if(!$start)
$start=0;
while($obj = $results->fetch_object()){
$applicationid=$obj->ApplicationID;
$start=0;
echo "<div class=\"col-4 col-sm-4 col-lg-4\">";
echo '<form method="post" action="cart_update.php">';
echo "<div id='product'><a href='appproduct.php?id=$applicationid'><img src='images/app_images/$applicationid.jpg' alt='Product picture'/></div>";
echo '<h2>'.$obj->ApplicationName.'</h2>';
echo '<p>'.$obj->ApplicationDescription.'</p>';
if($obj->App_cost=="0.00"){
echo '<p>Free</p>';
}else{
echo '<p>£'.$obj->App_cost.'</p>';
}
echo '<button class="add_to_cart">Add To Cart</button>';
echo '<input type="hidden" name="product_code" value="'.$obj->ApplicationID.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form><br /><br /></div>';
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$last = $max_pages - 1;
if($max_pages > 1){
//previous button
if (!($start<=0))
echo "<a href='index.php?os=$os=Search+source+code&start=$prev'>Prev |</a> ";
//pages
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++){
if($i == $start){
echo " <a href='index.php?os=$os=Search+source+code&start=$i'><b> $counter |</b></a> ";
}
else {
echo " <a href='index.php?os=$os=Search+source+code&start=$i'> $counter |</a> ";
}
$i = $i + $per_page;
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='index.php?os=$os=Search+source+code&start=$next'> Next</a> ";
}
echo "</center>"
?>
You should try to do the pagination via database, instead of loading all the results eagerly. If you had 100000 records and wanted to show only first 6 of them, you'd need to fetch 99994 records you might not use. Try to use limit of sql.
As for your problem with "bolding" current page number, you have logic error here:
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++) {
if($i == $start){
echo " <a href='index.php?os=$os=Search+source+code&start=$i'><b> $counter |</b></a> ";
} else {
echo " <a href='index.php?os=$os=Search+source+code&start=$i'> $counter |</a> ";
}
$i = $i + $per_page;
According to this snippet you are comparing $i to $start, where $i is always equal to 0, so it will bold anything only on first page.
You need to use LIMIT in your MySQL query to only get a page of results at a time. It will look something like LIMIT 0, 6.
change this line it will work
$results = mysqli_query($conn, "SELECT * FROM apps A INNER JOIN device D ON D.DeviceID = A.DeviceID WHERE D.DeviceName = '$os' LIMIT $_GET['start'], 6;");
but it's not the best way to do pagination or putting a variable straight from global variables. I would advise you to use at leat mysql escape string function in php
My question is rather lengthy, so I'll get right to it. I have a search engine set up that sends data (GET method) to a php script which queries a MySQL database and then displays the results. You can view the project, to get a better understanding, here: http://www.quinterest.org/testcategory/
The form consist of a search box as well as a multiple select option that narrow the search.
Everything thing works wonderfully, but there is one thing I would like to change and I don't know how. If someone could explain, in detail, what I need to do to be able to show the results (I figure it will be in a div written in the HTML?) from the query on the same page as the original form without the need to refresh the page?
If you would like an example, here is one: http://quizbowldb.com/search
The search stays on the same page.
P.S. I know the mysql_ functions are outdated. Please don't harass me. I'm all very new to this still and the mysql_ functions are simple, easy and good enough for what I need. When I get further programming experience (I'm still in middle school), I may convert it to PDO or MySQLi.
HTML Form:
<form action='search.php' method='GET' class="form-search">
<input type='text' placeholder="What would you like to learn about?" class="input-xxlarge search-query" id="inputInfo" name='search'><br></br>
<input type='submit' class="btn btn-large btn-primary" name='submit' value='Search'></br>
<select multiple="multiple" name='category[]'>
<option value="%">All</option>
<option>Literature</option>
<option>History</option>
<option>Science</option>
<option>Fine Arts</option>
<option>Trash</option>
<option>Mythology</option>
<option>Phylosophy</option>
<option>Social Science</option>
<option>Religion</option>
<option>Geography</option>
</select>
</center>
</form>
search.php
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
print $search;
//validating search term length and connecting to db
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b><em>$search</em></b> and ";
mysql_connect("fake","fake","fake");
mysql_select_db("quinterestdb");}
//validating search term for protection; if statement to avoid errors being displayed
if (strlen($search)>1){
mysql_real_escape_string($search);}
//exploding search with multiple words
$search_exploded = explode (" ", $search); //creates array of all terms in search
foreach($search_exploded as $search_each) //loops through array
{
$x++;
if($x==1)
$construct .="Answer LIKE '%$search_each%'"; //if only one value in array
else
$construct .="AND Answer LIKE '%$search_each%'"; //for each multiple value in array
}
$cat = $_GET ['category']; //preparing array (multiple choices)
if (is_array($cat))
{
foreach($cat as $val) //
{
if($val=="%") //if no category is selected
continue;
else //split array choices (separated by ' and ,)
$comma_separated = implode("','", $cat);
$newvar = "AND Category IN('$comma_separated')"; //if category is chosen
}
} //ignore for now
$constructs ="SELECT * FROM tossupsdb WHERE $construct $newvar"; //completed search query
//quering the database; if statement to avoid errors being displayed
if (strlen($search)>1){
$run = mysql_query($constructs);}
print "$constructs"; //ignore for now
//number of results found; if statement to avoid errors being displayed
if (strlen($search)>1){
$foundnum = mysql_num_rows($run);}
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
else
{
echo " <span class='badge badge-info'> $foundnum </span> results were found:<hr size='5'>";
$per_page = 25; //preparing for pagination; results that appear per page
$start = $_POST['start']; //where to start results on page
$max_pages = ceil($foundnum / $per_page); //number of pages there will be
if(!$start) //starting at 0
$start=0;
$getquery = mysql_query("SELECT * FROM tossupsdb WHERE $construct $newvar LIMIT $start, $per_page");
while($runrows = mysql_fetch_array($getquery)) //fetching results
{
$answer = $runrows ['Answer']; //obtaining individual data from database
$category = $runrows ['Category']; //obtaining individual data from database
$num = $runrows ['Question #']; //obtaining individual data from database
$difficulty = $runrows ['Difficulty']; //obtaining individual data from database
$question = $runrows ['Question']; //obtaining individual data from database
$round = $runrows ['Round']; //obtaining individual data from database
$tournament = $runrows ['Tournament']; //obtaining individual data from database
$year = $runrows ['Year']; //obtaining individual data from database
//what will be displayed on the results page
echo "<div class='alert alert-info' style='border-radius: 20px'><div style='padding: 10px'>
<span class='label label-info' font-size='30px'><em>Tournament | Year | Round | Question # | Category</em></span></div>
<b>$tournament |</b> <b>$year |</b> <b>$round |</b> <b>$num |</b> <b>$category</b>
<p><em>Question:</em> $question</p>
<div class='alert alert-info'><em><strong>ANSWER:</strong></em> $answer</div></div><hr>
";
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a class='btn btn-primary btn-large' href='search.php?search=$search&submit=Search+source+code&start=$prev'>Prev</a> ";
//pages
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a class='btn btn-primary btn-large' href='search.php?search=$search&submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
?>
You need to use AJAX to do that. Using AJAX, you send asynchronous requests (requests without loading the page) to the server.
This is how Google and other major search engines work. Learn about it here : Ajax tutorial
Ajax - Asynchronous JavaScript And XML
From Wikipedia definition of Ajax:
With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
Data can be retrieved using the XMLHttpRequest object.
Despite the name, the use of XML is not required (JSON is often used instead), and the requests do not need to be asynchronous.
The simplest way to accomplish this is probably via jQuery, a JavaScript framework; by "simple", I mean the least work on your end:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
// This is the equivalent of the older $(document).ready() event
$(function(){
$('#search-form').on('submit', function(event){
event.preventDefault(); // prevents form submission
var data = $('#search-form').serialize(); // get all of the input variables in a neat little package
var action = $('#search-form').attr('action'); // get the page to get/post to
$.get(action, data, function(response, status, jqxhr){
$('#target').html(response);
});
});
});
</script>
Here, I add an id to your form so that I can directly target it. I also assume that there is a HTML element with an id of target that I can inject with the response HTML (which I also assume is only a fragment).