I am building a navigation system on a webpage using PHP, that basically queries data from MySQL database and display as ul, li menu on main menu. But I couldn't figure out how do I make navigation menu selected when user goes to that page. I have one idea but that doesn't make home menu selected by default when user enters that page.
I have also a CSS class written to give that class to the anchor tag if it is that page.
here is my PHP code:
//Query Functions
function queryMenu() {
$query = "SELECT * FROM menu_en";
return $query;
}
// Render Functions
function renderNav() {
$menus = queryMenu();
$queryMenu = mysql_query($menus);
while( $navigation = mysql_fetch_array($queryMenu) ){
if( $navigation['id'] == $_GET['pageId'] ){
echo '<li>
<a href="index.php?pageId="'.$navigation['id'].' class="selected" >'.$navigation['menu_title'].
'</a></li>';
}else{
echo '<li><a href="index.php?pageId="'.$navigation['id'].'>'.$navigation['menu_title'].'</a></li>';
}
}
}
Suggest me a better way to do this, as I want to enhance my skill in PHP. And also please let me know if there is any wrong approach in above code.
If the home page is when $_GET['pageId'] is not set you could check using isset()
if(isset($_GET['pageId'])) {
$page = $_GET['pageId']
} else {
$page = $homePageId; // the ID of the home page.
}
Then you would replace this line:
if( $navigation['id'] == $_GET['pageId'] ){
with this line:
if( $navigation['id'] == $page ){
I think this would work, if i understand you correctly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.