Page view in php - php

I have to make a small adjustment on a website, the problem comes on the page.
For example I have a page with 11 button, these 1 I do not have to show them at once, but I have for example I have to show the first 5 and then the page has to be moving but I never have to stop showing 5 results on the page.
I leave reference images:
This is the way the page does NOT have to look:
This is the way the page should look:
for example if I get to 7 that 3 is no longer shown and shows me 8
This is my code
<nav>
<ul class="pagination">
<?php if ($pagina == 1) : ?>
<li class="page-item disabled">
<a class="page-link" href="">
<span class="ti-arrow-left"></span>
</a>
</li>
<?php else : ?>
<li class="page-item">
<a class="page-link" href="?pagina=<?php echo $pagina - 1 ?>">
<span class="ti-arrow-left"></span>
</a>
</li>
<?php endif; ?>
<!---------------------------------------------------------------------->
<?php
for ($i = 1; $i <= $numeroDePaginas; $i++) {
if ($pagina == $i) {
echo "<li class='page-item active'>
<a class='page-link' href='?pagina=$i'>$i</a>
</li>";
} else {
if (($i + 2) < $pagina || ($i - 2) > $pagina) {
echo "<li class='page-item'>
<a class='page-link' href='?pagina=$i'>$i</a>
</li>";
}
}
}
?>
<!---------------------------------------------------------------------->
<?php if ($pagina == $numeroDePaginas) : ?>
<li class='page-item disabled'>
<a class='page-link' href=''>
<span class='ti-arrow-right'></span>
</a>
</li>
<?php else : ?>
<li class='page-item'>
<a class='page-link' href="?pagina=<?php echo $pagina + 1 ?>">
<span class='ti-arrow-right'></span>
</a>
</li>
<?php endif; ?>
</ul>
</nav>

Here you go. I have added next_pages variable and previous_pages variables, which will make sure to get the pagina - 2 and pagina + 2 if exists. Let me know if you need help understanding it.
<nav>
<?php
$next_pages = ($pagina + 2) <= $numeroDePaginas ? $pagina + 2 : $numeroDePaginas;
$previous_pages = ($pagina - 2) >= 1 ? $pagina - 2 : 1;
?>
<ul class="pagination">
<?php if ($pagina == 1) : ?>
<li class="page-item disabled">
<a class="page-link" href="">
<span class="ti-arrow-left"></span>
</a>
</li>
<?php else : ?>
<li class="page-item">
<a class="page-link" href="?pagina=<?php echo $pagina - 1 ?>">
<span class="ti-arrow-left"></span>
</a>
</li>
<?php endif; ?>
<!---------------------------------------------------------------------->
<?php
for ($i = $previous_pages; $i <= $next_pages; $i++) {
if ($pagina == $i) {
echo "<li class='page-item active'>
<a class='page-link' href='?pagina=$i'>$i</a>
</li>";
} else {
echo "<li class='page-item'>
<a class='page-link' href='?pagina=$i'>$i</a>
</li>";
}
}
?>
<!---------------------------------------------------------------------->
<?php if ($pagina == $numeroDePaginas) : ?>
<li class='page-item disabled'>
<a class='page-link' href=''>
<span class='ti-arrow-right'></span>
</a>
</li>
<?php else : ?>
<li class='page-item'>
<a class='page-link' href="?pagina=<?php echo $pagina + 1 ?>">
<span class='ti-arrow-right'></span>
</a>
</li>
<?php endif; ?>
</ul>
</nav>
Edit with more explaination:
I have added a variable called next_pages, this variable checks if the current page (ex: 9) + 2 is smaller than or equal to "numeroDePaginas" variable, I have done this to make sure that we never show any pages exceeding the number of pages we have, in case 9+2 is bigger than "numeroDePaginas" we set the variable equal to "numeroDePaginas"
For the previous_pages variable, we make sure that the current page(ex: 3) - 2 is never less than 1, (so it doesn't show 0 or negative pages for example), in case
3-2 is smaller than 1, we set the variable to 1.
Now, I have edited the for loop, to make sure that it starts from the previous_pages variable, and ends with next_pages variable.
Here are a test case:
$pagina = 7;
$numeroDePaginas = 9;
//$next_pages will be = 9 (i.e 7+2)
//$previous_pages will be = 5 (i.e 7-2)
for loop would print pages from 5 to 9.

Related

Could not get the id from the url when switching pages in pagination

I'm having trouble getting the id from the URL when i'm switching to another page using the pagination, I need this id from the database to view the contents in the navbar when i switch to another page. When I try to switch to pages the contents in the navbar will not appear. Here is my code
<?php
$limit = 5;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $limit;
$sql = "SELECT * FROM invoice LIMIT $start, $limit";
$result1 = $conn->query("SELECT count(id) AS refNo FROM invoice");
$query = mysqli_query($conn,$sql);
$custCount = $result1->fetch_all(MYSQLI_ASSOC);
$total = $custCount[0]['refNo'];
$pages = ceil($total / $limit);
$previous = $page - 1;
$next = $page + 1;
$id = $_GET['id2'];
?>
<h3 class="text-center" style="color:white">Student Schedules</h3>
<label for="course" style="color:white">Invoices And Records<br></label>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="viewUserSchedule.php?id=<?php $id?>&page=<?= $previous; ?
>">Previous</a></li>
<?php for($i = 1; $i <= $pages; $i++) : ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php $id?
>&page=<?= $i; ?>
"><?= $i ?></a></li>
<?php endfor; } ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php $id?
>&page=<?= $next; ?>">Next</a></li>
</ul>
</nav>
Just change this:
<?php $id?>
to this:
<?= $id ?>
or this:
<?php echo $id ?>
As I can see in your codes, you have simple mistake in your codes.
You are using:
<?php $id?>
and for other variables like $previous you are using:
<?= $previous; ?>
So <?= is shortcode for <?php echo and in printing your $id variable you missed the echo
So, you should use :
<?php echo $id?>
Or
<?= $id?>
so try this code, and it would work for you:
<h3 class="text-center" style="color:white">Student Schedules</h3>
<label for="course" style="color:white">Invoices And Records<br></label>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="viewUserSchedule.php?id=<?php echo $id?>&page=<?= $previous; ?>">Previous</a></li>
<?php for($i = 1; $i <= $pages; $i++) : ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php echo $id?>&page=<?= $i; ?>"><?= $i ?></a></li>
<?php endfor; } ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php echo $id?>&page = <?= $next; ?>">Next</a></li>
</ul>
</nav>

Combine for and if statements

I've been researching if this is possible, but I've drawn a blank, I'm wondering if it's possible to optimize these for and if statements together? cheers.
Edit (Updated #2) : Their is an issue with the code not looping through the pages.
<?php
// calculate total number of pages
$total_pages = ceil($total_rows / $records_per_page);
// range of links to show
$range = 2;
// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range) + 1;
?>
<ul class="pagination margin-zero">
<?php if ($page>1) : ?>
<li>
<a href='<?php echo $page_url; ?>page=1' title='Go to the first page.'>First Page</a>
</li>
<?php endif; ?>
<?php
for ($x = min($initial_num, 0); $x <= max($condition_limit_num-1, $total_pages); $x++) :
if ($x == $page) :
?>
<li class='active'>
<?php echo $x; ?> <span class="sr-only">(current)</span>
</li>
<?php else : ?>
<li>
<a href='<?php echo $page_url; ?>page=<?php echo $x; ?>'><?php echo $x; ?></a>
</li>
<?php
endif;
endfor;
?>
<?php
if ($page<$total_pages) : ?>
<li>
<a href='<?php echo $page_url; ?>page=<?php echo $total_pages; ?>' title='Last page is <?php echo $total_pages; ?>'>
Last Page
</a>
</li>
<?php endif; ?>
</ul>
Of course you can combine them if you think about the maximum and minimum value that $x is allowed to get assigned.
The outer for loop would require $x to be contained in the interval [0; $condition_limit_num)
If you look only at the for and the first if you could decide that the minimum has to be larger than zero or initial_num, so you could for example use the minimum of initial_num and zero. The limit would work the same way using the maximum of condition_limit_num-1 and total_pages as uppermost reachable value, i.e. the interval [min($x, 0); max($condition_limit_num-1;$total_pages)].
But if you take into account the innermost if you require $x to have a specific value ($page). That means that this if is only "true" whenever $page is contained in the intervall [min($x, 0); max($condition_limit_num-1;$total_pages)] - you can reduce that check to a single if.
Update after question update:
Since the innermost if also has an else path the loop cannot be reduced to a single if:
<?php
for ($x = max($initial_num, 0); $x <= min($condition_limit_num-1, $total_pages); $x++)) :
if($x == $page) :
?>
<li class='active'>
<?php echo $x; ?> <span class="sr-only">(current)</span>
</li>
<?php else : ?>
<li>
<a href='<?php echo $page_url; ?>page=<?php echo $x; ?>'><?php echo $x; ?></a>
</li>
<?php
endif;
endfor;
?>

PHP Pagination Display

I'm using bootstrap pagination, and a combination PHP/mysql method of displaying my results, (ex. results.php?results=1 for each page). This is working fine, but actually displaying the pagination div at the bottom of my page, i.e. which one is active, whether or not you can click the following or preceding items (if there actually are results on those pages)
So I've done a specific case for just about every combination I could think of that would affect anything, but it is certainly not efficient. Can anyone suggest a better way to do it? Some of the cases will be obvious, like if I'm on page one, I don't want to show page 0 and -1 in the pagination, others are less obvious, like if I'm on page 3, and there are no more pages, I want page 3 to be in the middle, as there are 5 numbers displayed, but you should not be able to click on 4 and 5.
I'm using an exact replica of the plugin showed here except I've added left and right increase / decrease by one in addition to the first / last page.
<div id="pagination" style="width: 340px; margin-left: auto; margin-right: auto;">
<? if ($results == 1) { ?>
<ul class="pagination">
<li class="disabled"> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li class="disabled"> <i class="fa fa-lg fa-angle-left"></i> </li>
<li class="active"><? echo $results; ?> <span class="sr-only">(current)</span></li>
<li <?if ($num_rows < $num_res) { echo "class=\"disabled\""; } ?>><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 2)) { echo "class=\"disabled\""; } ?>><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 3; ?></li>
<li <?if ($num_rows < ($num_res * 4)) { echo "class=\"disabled\""; } ?>><? echo $results + 4; ?></li>
<li <?if ($num_rows < ($num_res)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if ($results == 2) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results; ?> <span class="sr-only">(current)</span></li>
<li <?if ($num_rows < ($num_res * 2)) { echo "class=\"disabled\""; } ?>><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 3; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results == 3) && (($last_page == 3))) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 2; ?> </li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results; ?><span class="sr-only">(current)</span></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results > 2) && ($results < ($last_page - 1))) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 2; ?> </li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results; ?><span class="sr-only">(current)</span></li>
<li><? echo $results + 1; ?></li>
<li><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results > 2) && ($results == ($last_page - 1))) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 3; ?></li>
<li><? echo $results - 2; ?></li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results ?><span class="sr-only">(current)</span></li>
<li><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results > 2) && ($results == $last_page) && ($results != 3)){ ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 4; ?> </li>
<li><? echo $results - 3; ?></li>
<li><? echo $results - 2; ?></li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results ?><span class="sr-only">(current)</span></li>
<li class="disabled"> <i class="fa fa-lg fa-angle-right"></i> </li>
<li class="disabled"> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
</div>
If no one feels like helping with the first portion, I understand, it works as it is as far as I can tell.
But I also am wondering if there's a way that on my class="disabled", I can remove the hrefs? Or do I just have to put an if statement on every one? Thanks.
Edit: Based on #Scopey's recommendations. I changed a few things as I saw fit, as well as a couple variable names.
$numberOfPages = ceil($num_rows / $num_res);
$numberOfPages = (int)$numberOfPages;
$url = explode('&', $_SERVER['REQUEST_URI']);
function myFilter($string) {
return strpos($string, 'results=') === false;
}
$url = array_filter($url, 'myFilter');
$url = implode('&', $url);
?>
<ul class="pagination">
<li<?php if($results === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== $numberOfPages){
echo $url.'&results=' . 1;
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-double-left"></i> </a></li>
<li<?php if($results === 1): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== 1){
echo $url.'&results=' . ($results - 1);
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-left"></i> </a></li>
<?php
// Print the pagination...
// Minimum of 5 pages in the pagination, even if there aren't 5 pages...
$pageCount = ($numberOfPages < 5) ? 5 : $numberOfPages;
// Loop through from page 1 until the last page ($pageCount)
for($i = 1; $i <= $pageCount; $i++)
{
// Echo out just the beginning of the <li> tag as we don't yet
// know if this needs to be disabled...
echo '<li';
// Added to show if current page is active
if($i === $results) {
echo ' class="active"';
}
// Check if:
// - This current page is greater than the amount of pages of
// results we have
// - OR, this is the currently selected page
if($i > $numberOfPages || $results === $i)
{
// <li> tag needs the disabled class....
echo ' class="disabled"';
}
// Finish the <li> tag and start generating the link
echo '><a href="';
// Opposite logic from above... Only if this is a page we know about
// AND this is not the current page.
if($i < $numberOfPages && $results !== $i)
{
// The link will be your page, with the get param, and the
// current page number we're printing
echo $url.'&results=' . $i;
}
else
{
// Otherwise just a # (no link)
echo '#';
}
// Finish this page... Print the page number ($i)
echo '">' . $i . '</a></li>';
}
?>
<li<?php if($results === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== $numberOfPages){
echo $url.'&results=' . ($results + 1);
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-right"></i> </a></li>
<li<?php if($results === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== $numberOfPages){
echo $url.'&results=' . $numberOfPages;
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-double-right"></i> </a></li>
<?php
#Scobey, this works great, as intended, and same as my original post, except for a couple things. In my example, I was able to get the current page in the middle of the . For example, << 1 | 2 | 3 | 4 | 5 >>, that's why I had so many different statements with +1 and -1, +2, -2 etc.
Second, my intention was to display 5 page options at all times, not just a minimum of five. So if I was on page 6, I would only see << 4 | 5 | 6 | 7 | 8 >>, not 1-8. It may not be necessary to do it this way, it's a nice to have. But, I don't want to get to a point where I have over 50 different page numbers in the pagination.
Generally dynamic pagination works only when you have a few things
A count of all possible results (total)
An amount of results you want to show per page
The current page number
Information about the results that should appear on this page.
Imagine that you have a database table called Results that has a whole bunch of results you want on your paginated page
1. Count of all possible results
This is achievable with a simple SQL statement like:
SELECT count(*) FROM Results
2. Amount per page
This is a value you get to decide yourself.
3. The current page number
This is usually 1 by default, but when the pagination is changed, it gets passed through as a get parameter.
4. A slice of results from the table
Achievable with:
SELECT * FROM Results LIMIT 0, 20
This example retrieves the first 20 results in our results table...
5. The pagination
Now, using 20 results as a default "count per page"
$countPerPage = 20;
// Get the total number of results
$result = pg_query('SELECT count(*) FROM Results'); // I'm using PostgreSQL for this example
$totalResultCount = (int)pg_fetch_result($result, 0, 0);
// The ceil function will round floats up.
$numberOfPages = ceil($totalResultCount / $countPerPage);
// Check if we have a page number in the _GET parameters
if(!empty($_GET) && isset($_GET['page']))
{
$page = (int)$_GET['page'];
}
else
{
$page = 1;
}
// Check that the page is within our bounds
if($page < 0)
{
$page = 1;
}
elseif($page > $numberOfPages)
{
$page = $numberOfPages;
}
// Build the query for the results...
$query = 'SELECT * FROM Results LIMIT ' . ($page - 1) * $countPerPage . ', ' . $countPerPage;
$results = pg_fetch_all(pg_query($query));
// Deal with printing your results etc...
?>
<ul class="pagination">
<li<?php if($page === 1): ?> class="disabled"<?php endif; ?>><a href="<?php
if($page !== 1){
echo 'page.php?page=' . $page - 1;
} else { echo '#'; }
?>">«</a></li>
<?php
// Print the pagination...
// Minimum of 5 pages in the pagination, even if there aren't 5 pages...
$pageCount = ($numberOfPages < 5) ? 5 : $numberOfPages;
// Loop through from page 1 until the last page ($pageCount)
for($i = 1; $i < $pageCount; $i++)
{
// Echo out just the beginning of the <li> tag as we don't yet
// know if this needs to be disabled...
echo '<li';
// Check if:
// - This current page is greater than the amount of pages of
// results we have
// - OR, this is the currently selected page
if($i > $numberOfPages || $page === $i)
{
// <li> tag needs the disabled class....
echo ' class="disabled"';
}
// Finish the <li> tag and start generating the link
echo '><a href="';
// Opposite logic from above... Only if this is a page we know about
// AND this is not the current page.
if($i < $numberOfPages && $page !== $i)
{
// The link will be your page, with the get param, and the
// current page number we're printing
echo 'page.php?page=' . $i;
}
else
{
// Otherwise just a # (no link)
echo '#';
}
// Finish this page... Print the page number ($i)
echo '">' . $i . '</a></li>';
}
?>
<ul class="pagination">
<li<?php if($page === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($page !== $numberOfPages){
echo 'page.php?page=' . $page + 1;
} else { echo '#'; }
?>">»</a></li>
<?php
Disclaimer
I just sat here and wrote this, I have not tested it, but the general idea is there. Hopefully it makes sense. I'm running out of time and don't have time to test or improve it, but if you're interested I might fix it up later.
Hope this helps!

Why am I getting duplicate <a> tags?

I'm using the bootstrap "pager" found in the pagination section.
Here is what I'm using to load the HTML of it in PHP:
echo "<ul class='pager'>";
echo ($total > $lim) ? "<li class='previous'>" : "<li class='previous disabled'>";
echo ($total > $lim) ? "<a href='#status' onclick='getStatuses(" . (($lim+10)/10) . ")'>← Older</a>" : "<a>← Older</a>";
echo "</li>";
echo ($lim == 10) ? "<li class='next disabled'>" : "<li class='next'>";
echo ($lim == 10) ? "<a>Newer →</a>" : "<a href='#status' onclick='getStatuses(" . (($lim-10)/10) . ")'>Newer →</a>";
echo "</li>";
echo "</ul>";
Now, when I actually load this, it returns like this:
<ul class="pager">
<a></a>
<li class="previous disabled">
<a></a>
<a>← Older</a>
</li>
<li class="next disabled">
<a>Newer →</a>
</li>
</ul>
There are 2 what seem to be random <a></a> tags. How can I get rid of these? What am I doing wrong?
Printing out a bunch of HTML from PHP usually leads to code comprehension difficulties. Better to drop out of the PHP context for the most part, for example
// drop out of PHP
?>
<ul class="pager">
<?php if ($total > $lim) : ?>
<li class="previous">
← Older
</li>
<?php else : ?>
<li class="previous disabled">
<a>← Older</a>
</li>
<?php endif ?>
<?php if ($lim == 10) : ?>
<li class="next disabled">
<a>Newer →</a>
</li>
<?php else : ?>
<li class="next">
Newer →
</li>
<?php endif ?>
</ul>
<?php
// and now back to PHP
Agreed with Phil, but my guess would be the &larr or the fact that you don't have parenthesis around your ternary expressions. Try this:
echo "<ul class='pager'>";
echo (($total > $lim) ? "<li class='previous'>" : "<li class='previous disabled'>");
echo (($total > $lim) ? "<a href='#status' onclick='getStatuses(" . (($lim+10)/10) . ")'> Older</a>" : "<a> Older</a>");
echo "</li>";
echo (($lim == 10) ? "<li class='next disabled'>" : "<li class='next'>");
echo (($lim == 10) ? "<a>Newer →</a>" : "<a href='#status' onclick='getStatuses(" . (($lim-10)/10) . ")'>Newer</a>");
echo "</li>";
echo "</ul>";

Add class="active" to active page using PHP

Dynamic Header, CSS Class Change To Active USING PHP (dirrectory)
I want the class of the <li> tag to change under the active dirrectory...
now, every guide shows me how to do it when your page equals it, but i want to change
the <li> depending on what dirrectory im on
for example:
if say im on http://example.com/RESOURCES/code/opensource, or http://example.com/RESOURCES/images/clipart i want the "RESOURCES" ^^ <li> to be 'class="active"' while the rest display 'class="noactive"'
or if im on http://example.com/tutorials/css/flawless-dropdown-menu I want the "tutorials" <li> to be 'class="active"' while the rest are 'class="noactive"'
URL Setup:
This is my example of how my url's are displayed...
http://example.com/tutorials/css/flawless-dropdown-menu
^^That URL is the page of a tutorial....under the "tutorials" directory, than under the "CSS" category directory, than the page title (all of these directories are not real and are rewrites from .htaccess) [irrelevant]
Navigation Setup:
<ul id="mainnav">
<li class="noactive">Home</li>
<li class="active">Tutorials</li>
<li class="noactive">Resources</li>
<li class="noactive">Library</li>
<li class="noactive">Our Projects</li>
<li class="noactive">Community</li>
</ul>
Figured out the ANSWER...I was over thinking it.
HTML
<ul id="mainnav">
<li class="<?php if ($first_part=="") {echo "active"; } else {echo "noactive";}?>">Home</li>
<li class="<?php if ($first_part=="tutorials") {echo "active"; } else {echo "noactive";}?>">Tutorials</li>
<li class="<?php if ($first_part=="resources") {echo "active"; } else {echo "noactive";}?>">Resources</li>
<li class="<?php if ($first_part=="library") {echo "active"; } else {echo "noactive";}?>">Library</li>
<li class="<?php if ($first_part=="our-projects") {echo "active"; } else {echo "noactive";}?>">Our Projects</li>
<li class="<?php if ($first_part=="community") {echo "active"; } else {echo "noactive";}?>">Community</li>
</ul>
PHP
<?php
$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);
$first_part = $components[1];
?>
header.php
$activePage = basename($_SERVER['PHP_SELF'], ".php");
nav.php
<ul>
<li class="<?= ($activePage == 'index') ? 'active':''; ?>">Home</li>
<li class="<?= ($activePage == 'tutorials') ? 'active':''; ?>">Tutorials</li>
...
Through PHP you can try -
<?php
// gets the current URI, remove the left / and then everything after the / on the right
$directory = explode('/',ltrim($_SERVER['REQUEST_URI'],'/'));
// loop through each directory, check against the known directories, and add class
$directories = array("index", "tutorials","resources","library","our-projects","community"); // set home as 'index', but can be changed based of the home uri
foreach ($directories as $folder){
$active[$folder] = ($directory[0] == $folder)? "active":"noactive";
}
?>
<ul>
<li class="<?php echo $active['index']?>">Home</li>
<li class="<?php echo $active['tutorials']?>">Tutorials</li>
<li class="<?php echo $active['resources']?>">Resources</li>
<li class="<?php echo $active['library']?>">Library</li>
<li class="<?php echo $active['our-projects']?>">Our Projects</li>
<li class="<?php echo $active['community']?>">Community</li>
</ul>
Maybe this helps you:
$(document).ready(function()
{
var parts = document.URL.split("/");
// [http:, empty, your domain, firstfolder]
var firstFolder = parts[3];
$("#mainnav li").attr("class", "noactive");
$("#mainnav a[href='/" + firstFolder + "/']").parent().attr("class", "active");
});
It's probably easier to do with jQuery but this works:
$url='http://example.com/tutorials/css/flawless-dropdown-menu';//pass the current url here instead of a static string.
$segments = explode ("/",$url);
$menuItems=array('Tutorials','Resources', 'Library', 'Our-Projects','Community');
$menu=array();
foreach ($menuItems as $menuItem) {
if($segments[3]==strtolower($menuItem)){
$menu[]=('<li class="active">'.str_replace("-"," ",$menuItem).'</li>');
} else {
$menu[]=('<li class="no-active">'.str_replace("-"," ",$menuItem).'</li>');
}
}
foreach ($menu as $item) {
echo $item.'<br />';
}
if you use mysql_fetch defined your row for menu title.
if we take your menu title is MENU in mysql database and you have to put in
(Home,tutorials,library,resources,our-projects,community)
<?php
//connect your data bass
include(connection.php');
//get your from ID like www.google?id=1
$id = $_GET['id'];
$query = "select * from pages where id='$id'";
$query1 = mysql_query($query);
while($row= mysql_fetch_array($query1))
{
?>
<html>
<?php $active= $row['MENU'];?>
<ul>
<li class="<?php if($active=='Home'){echo 'active';}else{echo'noactive';}?>">Home</li>
<li class="<?php if($active=='tutorials'){echo 'active';}else{echo'noactive';}?>">Tutorials</li>
<li class="<?php if($active=='resources'){echo 'active';}else{echo'noactive';}?>">Resources</li>
<li class="<?php if($active=='library'){echo 'active';}else{echo'noactive';}?>">Library</li>
<li class="<?php if($active=='our-projects'){echo 'active';}else{echo'noactive';}?>">Our Projects</li>
<li class="<?php if($active=='community'){echo 'active';}else{echo'noactive';}?>">Community</li>
</ul>
</html>
<?php };?>
This answer will apply if all your pages have a php extension and you want a long messy way. I put the code below on top of every php page giving each page an ID which means all pages will have an ID which is tiresome and boring and hard to track.
<?php $page = 1; ?>
Now in my header or navigation I used the code below to put the active class. You can also put an else if you want something else.
<nav id="navbar" class="navbar">
<ul>
<li class="<?php if($page == 1){ echo "active"; } ?>"><a class="url" href="index.php">Index</a></li>
<li class="<?php if($page == 2){ echo "active"; } ?>"><a class="url" href="single-post.php">Information</a></li>
<li class="<?php if($page == 3){ echo "active"; } ?>"><a class="url" href="single-post.php">Wanted</a></li>
<li class="<?php if($page == 4){ echo "active"; } ?>"><a class="url" href="single-post.php">Workshop</a></li>
<li class="<?php if($page == 5){ echo "active"; } ?>"><a class="url" href="gallery.php">Gallery</a></li>
<li class="<?php if($page == 6){ echo "active"; } ?>"><a class="url" href="featured.php">Featured</a></li>
<li class="<?php if($page == 7){ echo "active"; } ?>"><a class="url" href="contact.php">Contact Us</a></li>
</ul>
</nav>
"includes/header.php" - This goes in Top of the File
<?php
$activePage = basename($_SERVER['PHP_SELF']);
$index="";
$nosotros="";
$cursos="";
$contacto="";
switch ($activePage) {
case 'index.php':
$index=' class="current"';
break;
case 'nosotros.php':
$nosotros=' class="current"';
break;
case 'cursos.php':
$cursos=' class="current"';
break;
case 'contacto.php':
$contacto=' class="current"';
break;
default:
break;
}
?>
and this goes on the nav section
<ul>
<?php
echo '<li'.$index.'><div>Inicio</div></li>';
echo '<li'.$nosotros.'><div>Nosotros</div></li>';
echo '<li'.$cursos.'><div>Cursos</div></li>';
echo '<li><div>Academia</div></li>';
echo '<li><div>Tienda</div></li>';
echo '<li'.$contacto.'><div>Contacto</div></li>';
?>
</ul>
Try the following:
<ul class="sub-menu">
<div class="h-10"></div>
<li class="<?php if ($your_variable=="test") {echo "active"; }
else{echo"noactive";}?>">
Test
</li>
<li class="<?php if ($your_variable=="test2") {echo "active";
} else {echo"noactive";}?>">
<a href="test2.php" >Test2</a>
</li>
<li class="<?php if ($your_variable=="test3") {echo
"active"; } else {echo "noactive";}?>">
Test3
</li>
</ul>
**strong PHP text**
<?php
$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);
$your_variable = basename($_SERVER['PHP_SELF'], ".php");
?>
Here we can do a simple thing also :
<li class="page-scroll <?php if(basename($_SERVER['PHP_SELF'])=="aboutus.php"){echo "active";} ?>">About us</li>
Here is another take using PHP:
<ul class="navbar-nav">
<?php
// Defines all pages in navigation
$pages = array(
'Home' => 'index.php',
'Products' => 'products.php',
'Services' => 'services.php',
'Contact' => 'contact.php',
'About' => 'about.php'
);
// Gets active page URL
$active = basename($_SERVER['PHP_SELF']);
// Loops through all pages
foreach ($pages as $title => $url) {
// Checks if active url is matched and adds active CSS class
if ($active === $url) {
echo '<li>'.$title.'</li>';
}
// Prints out default style for remaining links
else {
echo '<li>'.$title.'</li>';
}
}
?>
</ul>
$getUrl = $_SERVER['REQUEST_URL']; -> www.example.com/home.php
$getFileName = explode('/',$getUrl);
The result of $getFileName Will Be In Array ->[" ","home.php"]
$result = $getFileName[2]; //home.php
<li class="<?php if ($result=='' || $result == 'index.php') {echo 'active'; }?>"><a href='#'>Home</a></li>
<li class="<?php if ($result=='about.php') {echo 'active'; }?>"><a href='#'>About Us</a></li>
<li class="<?php if ($result=='contact.php') {echo 'active'; }?>"><a href='#'>Contact Us</a></li>
You can use str_replace for this.
$path = $_SERVER['REQUEST_URI'];
$active = str_replace('/','', $path);
<ul>
<li class="nav-item <?php if($active == '' || $active == 'index.php'){echo 'active';}?>">
<a class="nav-link" href="index.php">HOME</a>
</li>
<li class="nav-item <?php if($active == 'about.php'){echo 'active';}?>">
<a class="nav-link" href="about.php">ABOUT US</a>
</li>
</ul>
<?php $request_uri= $_SERVER['REQUEST_URI'];?>
<ul>
<li class="<?php if((strpos($request_uri,"index.html")!==false) || $request_uri=="" || $request_uri=="/"){echo "selected";}?>">Home</li>
<li class="<?php if((strpos($request_uri,"service")!==false)){echo "selected";}?>">Services </li>
<li class="<?php if((strpos($request_uri,"product")!==false)){echo "selected";}?>">Products</li>
<li class="<?php if((strpos($request_uri,"blog")!==false)){echo "selected";}?>">Blog</li>
<li class="<?php if((strpos($request_uri,"question")!==false)){echo "selected";}?>">Ques & Ans</li>
<li class="<?php if((strpos($request_uri,"career")!==false)){echo "selected";}?>">Career</li>
<li class="<?php if((strpos($request_uri,"about-us")!==false)){echo "selected";}?>">About</li>
</ul>

Categories