Create page navigation using php - php

I am having some issues trying to create page navigation using php,
I have variable called $PageNo that I can navigate through using using next prev links -1 or +1.
eg.
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo+1)."'>Next</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo-1)."'>Prev</a>";
but aswell as this is want to display direct links to the pages so i have a navigation like so
PREV 1 2 3 4 NEXT
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo+1)."'>Next</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=1'>1</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=2'>2</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=3'>3</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=4'>4</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo-1)."'>Prev</a>";
If I know the total number of product pages is 4 how would you generate the links to give
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=1'>1</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=2'>2</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=3'>3</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=4'>4</a>";
Any help would be great.

How about to try this one?
// $total_num : total number of the pages
foreach (range(1, $total_num) as $p) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=$p"'>$p</a>";
}

You need to do the math, and then a little bit of code.
calculate the number os pages you need (based on the number os records and records per page)
Just use a for loop to do links like (not tested):
for ($page = 1; $page <= $total_pg; ++$page) {
echo "$page";
}
then, the product.php page reads that number and displays the subset of records

This is a simple for loop, and it's very basic stuff that's in all programming languages out there (just like if/else statements and while loops among others).
Say the total number of pages is 4, then you set a random variable, say $p (for pages) initially to it's start value 1, then continue the loop, increasing $p by 1 every time until $p is 4. Would result in this:
// Previous link before the numbers (unless we are on page 1)
if($PageNo > 1) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo-1)."'>Prev</a>";
}
// We loop over all the numbered pages here
for($p = 1;$p <= 4;$p++) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=" . $p . "'>" . $p . "</a>";
}
// Next link goes after the numbers (if there are any pages left)
if(($PageNo + 1) <= $p) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo+1)."'>Next</a>";
}

Related

How to use bootstrap pagination with php

I am a working with php and mysql and I managed to do pagination following this tutorial:
http://www.phpfreaks.com/tutorial/basic-pagination
Here is "mywebpage" (on work): http://ada.uprrp.edu/~ehazim/hpcf_proj/miejemplo.php
But Now, I want to make it "pretty" using bootstrap Pagination:http://getbootstrap.com/components/#pagination
I am using _GET['current_page'] to get the page where I am. The problem is that I dont know how to change the echo's to echo the pagination from bootstrap... Yes, it may be stupid, but It is my first time with php and I am like 2 hours just trying to do this. Can someone help me? Below is the code that I have, following the tutorial of php freaks (which I understand, except for some echos with toomany quotes :/ ):
<div class="pagination">
<ul>
<?php
/****** build the pagination links ******/
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
# TRYING TO CHANGE HERE AND IN OTHER ECHOS
#echo "<li>«</li>";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
#echo " <li><a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
# range of num links to show
$range = 3;
# loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
}
else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
# end build pagination links
?>
</ul>
</div>
To get you started, Bootstrap pagination works on a ul of class = pagination with the page links as list items.
Towards the start of your php code add the pagination class to the ul (not the div)
<ul class="pagination">
Then wherever you echo a page link, wrap it with li tags, e.g.
echo " <li><a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> </li>";
EDIT
You also want to tweak the HTML for the current page by changing
echo " [<b>$x</b>] ";
to
echo " <li>$x</li> ";
Edit
If you want to center your pagination bar, Bootstrap 3 has a the text-center class which you can use. See http://jsfiddle.net/panchroma/8RHzw/
Change the first line of your php to
<div class="text-center">
With Bootstrap 2, use
<div style="text-align:center;">
Hope this helps!
Further to David Taiaroa's answer above, for the active button state you need to add the class="active" and A tags.
echo " <li>$x</li> ";
..becomes..
echo " <li class=\"active\"><a>$x</a></li> ";

not to show previous link at the start page and next link at the last page?

I have to links Next and Previous in Pagination. What I should do so that 'previous' link should hide when I was on the first page and the 'next' link should hide when I was on the last page?
my code for next and previous links is:
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='
.($page-1).'&date1='.$_REQUEST["date1"].'&date2='.$_REQUEST["date2"].'">Previous</a>';
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='
.($page+1).'&date1='.$_REQUEST["date1"].'&date2='.$_REQUEST["date2"].'">Next</a>';
It wont work well the way your doing it right now, unless you have the specific number of pages.
If you have the total number of pages, you can do this
if( $page > 1 ) {
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='
.($page-1).'&date1='.$_REQUEST["date1"].'&date2='.$_REQUEST["date2"].'">Previous</a>';
}
if( $page < $totalPages ) {
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='
.($page+1).'&date1='.$_REQUEST["date1"].'&date2='.$_REQUEST["date2"].'">Next</a>';
}

PHP/MySQL Show first X results, hide the rest

Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? Basically, as I've already got the jquery, I just need to know how to show only the first X results in one div, then the rest in a seperate div.
My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.
Many thanks in advance. S
Thought I'd add the code I'm using below
$query = "SELECT * FROM ispress WHERE active = '1' ORDER BY YEAR(date) DESC, MONTH(date) DESC LIMIT 0, 7";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['date'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$bFirstTime = true;
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
echo '<div class="date">' . $timePeriod . '</div>' . PHP_EOL;
echo '<ul class="press">' . PHP_EOL;
foreach ($newsItems as $item)
{
if ($bFirstTime) {
echo '<li>';
echo '<img src="'.$wwwUrl.'images/news/'.$item['image'].'" width="'.$item['imgWidth'].'" height="'.$item['imgHeight'].'" title="'.$item['title'].'" alt="'.$item['title'].'" />
<h3>'.$item["title"].'</h3>
<p>'.substr($item['descrip'],0,244).'...</p>
<p>Read more</p>
';
echo '</li>' . PHP_EOL;
$bFirstTime = false;
} else {
echo '<li>';
echo '<img src="'.$wwwUrl.'images/news/'.$item['image'].'" width="'.$item['tnWidth'].'" height="'.$item['tnHeight'].'" title="'.$item['title'].'" alt="'.$item['title'].'" />
<h3>'.$item["title"].'</h3>
<p>'.substr($item['descrip'],0,100).'...</p>
<p>Read more</p>
';
echo '<div class="clear"></div>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
}
echo '</ul>' . PHP_EOL;
}
echo '<p>Older posts...</p>'. PHP_EOL;
echo '<div id="slickbox">This is the box that will be shown and display the rest of the news results. :)</div>'. PHP_EOL;
}
else
{
echo 'We currently have no press releases available';
}
This will hide the first 10 children. How are you planning on showing the other results? Buttons, fields, jqueryui widgets?
You will just need to add a click event which calls this function.
function limit_results(start, end) {
$('#things > .thing').each(index) {
if(index < end && index >= start) {
$(this).hide();
}
}
}
limit_results(1,10);
If you have your elements in a jQuery object already (say, $('#sql-results') holds all of your results), you can always do this: $('#sql-results:lt(10)') to work with the first ten elements, and $('#sql-results:gt(9)') to work with the rest of the elements.
You have to decide yourself how efficient your approach is for this amount of data you're processing.
Right, so for your specific markup structure, you can add this to your JS:
// Obviously this is untested and probably not bug-/typo-free
(
function($) {
var $slickbox = $('#slickbox').hide();
$('<ul></ul>')
.appendTo($slickbox)
.append('ul.press li:gt(9)');
$('#slick-toggle')
.bind(
'click',
function(){
$slickbox.toggle();
}
);
}
)(jQuery);
This would involve a lot of rewriting but jquery has a datatables plugin that will display the data. To use it you need to do something like
echo '<table id="news-table">'
echo '<thead>';//Datatables needs a thead with the correct number of columns. However you don't need to fill them in.
echo '<th>Date</th>';
echo '<th>Time Period</th>'
echo '</thead><tbody>';
while ($data = my_sql_fetch_array($result)) {
echo '<td>Whatever</td>';
echo '<td>Another Field</td>';
}
echo '</tbody></table>';
The jquery is then
$('#news-table').dataTable();
I'm not sure how it would do custom no data messages and I know that with the code you have written this may not be any good to you right now but I'm posting it because it could be useful for somebody looking for pagination info or for you if you want to do something similar again. Datatables is also useful because the user can choose the number of results they want to show, what column they want to sort by and what direction to sort in.
in your query
limit 0,10
for the rest
limit 11,xxx
When you print out each row's data count each iteration by incrementing a counter. When you get to 11 start a new div that has a different id to that of your 1st div that you already defined an id for. Now using jQuery you can hide and show the 2nd div with the remaining results as you please.
Divide the return values in your php file with a character
ex:
echo "this is first value +";
echo "this is second value +";
echo "this is third value +";
use javascript to separate the return values
ex:
var ajaxArray = ajaxValues.split("+");
now all three values are placed in ajaxArray and you may use anyone you want
ex:
ajaxArray[0] = this is first value

Multi column dynamic PHP list

So what I'm trying to do is select all the distinct months from my database and then print them in a list. That, I can accomplish. The problem lies in the fact that I need my list to be two column. The way that I achieve this with CSS is by using 2 different div's "left" and "right" which are floated next to each other. This poses a problem with PHP because it needs to echo a div close and a new div open after it echoes the sixth month. Then it needs to start again from where it left off and finish. I can't just list all of the months in the HTML, either because I don't want it to list a month if I don't have any records in the DB for that month, yet. Any ideas? I hope I was clear enough!
Thanks!
-williamg
Something like this should work (the basic idea being to just keep a count of the months an increment it as you loop through them):
<div class="left">
<?php
$x = 1;
foreach($months as $month) {
# switch to the right div on the 7th month
if ($x == 7) {
echo '</div><div class="right">';
}
echo "<div class=\"row\">{$month}</div>";
# increment x for each row
$x++;
}
</div>
<?php
$numberOfMonths = count($months);
$halfwayPoint = ceil($numberOfMonths / 2);
echo "<div class=\"left\">";
for($i=0; $i<$halfwayPoint; $i++){
echo $months[$i] . "<br />";
}
echo "</div><div class=\"right\">";
for($i=$halfwayPoint; $i<$numberOfMonths; $i++){
echo $months[$i] . "<br />";
}
echo "</div>";
?>
Rant: on
When displaying tabular data, use table instead of floating div. It will make sense when viewing the page with css disabled. If you use floated div, then you data will displayed all way down. Not all table usage is bad. People often hate table so much, so using floated div. Table only bad when used for page layout.
Rant: off
When I need to have certain content displayed with some open, close, and in-between extra character, I will make use of implode. This is the example:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
You can extends this to almost anything. Array and implode is the power that php have for many years. You will never needed any if to check if it last element, then insert the closing character, or check if it first element, then insert opening character, or print the additional character between elements.
Hope this help.
Update:
My bad for misread the main problems asked. Sorry for the rant ;)
Here is my code to make a data displayed in 2 column:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
Other solution is using CSS to format the output, so you just put the div top to down, then the css make the parent container only fit the 6 item vertically, and put the rest to the right of existing content. I don't know much about it, since it usually provided by fellow css designer or my client.
Example assumes you have an array of objects.
<div style="width:150px; float:left;">
<ul>
<?php
$c = count($categories);
$s = ($c / 3); // change 3 to the number of columns you want to have.
$i=1;
foreach($categories as $category)
{
echo '<li>' . $category->CategoryLabel . '</a></li>';
if($i != 0 && $i % $s == 0)
{
?>
</ul>
</div>
<div style="width:150px; float:left;">
<ul>
<?php
}
$i++;
}
?>
</ul>
</div>

Show each date only once

All right, this must be an absolutely easy question, and I apologize for that.
I also apologize if I simply failed in finding the right search terms to use to come to an answer on my own. I did try, but my lack of fluency in PHP kind of makes me suck at searching.
I'm looking for a simple way to show each date only once within a foreach loop. I'm looping through data like so:
<?php
echo "<ul>";
foreach($rss_items as $i){
if($i->get_feed()->get_title() == 'Twitter (no # replies)'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Twitter</a>";
echo $i->get_title();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Pinboard (jpcody)'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Pinboard</a>";
echo $i->get_title();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Entries at Church Marketing Sucks by Joshua Cody'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Church Marketing Sucks</a>";
echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
echo $i->get_description();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Flickr remove first paragraph'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Flickr</a>";
echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
echo $i->get_description();
echo "</li>";
}
}
echo "</ul>";
?>
And each item contains the date, so I'm getting the same date multiple times. I'd like to only have each date shown once, a la http://daringfireball.net.
I'm using CodeIgniter and the SimplePie library, so all of the data is being pulled directly instead of being stored in a db. I imagine a way to do it could be including a second if statement to check if the date has already been used, but I don't know how to execute this.
I'm pretty new to PHP, and I'm really looking to learn more than just have a solution given.
Any help you could give would be great!
You need to remember what was the date you used last, and print it only if it differs. You can try something like:
$previous_date = null;
foreach ($rss_items as $item) {
if ($item->get_date() != $previous_date) {
$previous_date = $item->get_date();
echo '<li>' . $previous_date . '</li>';
}
...
}
(And don't forget to HTML-encode the titles and links using htmlspecialchars.)
Do you mean you only want the date to be shown once, before the loop, or once per loop so that it looks like:
Date 1
- item 1
- item 2
- etc...
Date 2
- item 1
- item 2
- etc...
Could you clarify the format? Cause at the moment the date should be shown once for each $i that is valid.

Categories