Highlight Current Page on DYnamic Navigation PHP

2019-09-09 16:53发布

问题:

I get my dynamic navigation menu from the database because I have a CMS, so here's my code:

<ul>
<?php
$result = mysql_query("SELECT id, name, DESCRIPTION FROM menu where VISIBLE='1' ORDER BY `order` ASC") or die(mysql_error());                   
while($row = mysql_fetch_array($result)){
printf('<li>%s %s </a></li> ', $row['name'],$row['DESCRIPTION']);
}
?>

to highlight the current page, i have to add this inside the li element

how should i do this? Thanks in advance.

回答1:

u can try the following code

<?php 
$currentpage = $_SERVER['REQUEST_URI'];?>

<ul>

<?php

$result = mysql_query("SELECT id, name, DESCRIPTION FROM menu where VISIBLE='1' ORDER BY
 `order` ASC") or die(mysql_error()); 

while($row = mysql_fetch_array($result))
{
 ?>
<li<?php  if(preg_match("/index/i", $currentpage)||($currentpage=="/")) { echo " 
class='active'";     } ?>><a href="index.php">Home</a></li>


<?
 }
?>

instead of index you can also write $row[name] in a variable and replace /index/i with it



回答2:

set a variable on the page like

$navlink = '<somevalue>'

and check the the value in li

<li <?php if($navlink == '<somevalue>') {echo "class='active'"}?>>

i think it will work.