I am trying to build a menu with an active page element for CSS using PHP and MySQL.
This example PHP/HTML hybrid works, and is what I’m trying to mimic.
<nav><ul>
<li<?php if ($thisPage == "1") echo " class=\"active\""; ?>><a href="pg1.php">page 1</a></li>
<li<?php if ($thisPage == "2") echo " class=\"active\""; ?>><a href="pg2.php">page 2</a></li>
<li<?php if ($thisPage == "3") echo " class=\"active\""; ?>><a href="pg3.php">page 3</a></li>
</nav></ul>
I want to blend this statement to set the active class:
<?php if ($thisPage == $menuID) echo " class=\"active\""; ?>
Into this unordered list statement
<?php
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
echo "<li>" . "<a href=\"" . $row_rsMenu['menuURL'] . "\">" . $row_rsMenu['menuName'] . "</a></li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
?>
This is where I am but I can’t seem to get the syntax to work correctly.
echo "<li" . "if(" . $thisPage==$menuID . ")". echo ' class=\"active\"';" . ">" . "<a href=\"" . $row_rsMenu['menuURL'] . "\">" . $row_rsMenu['menuName'] . "</a></li>\n";
If someone could help me to understand where this went wrong I’d appreciate it.
You have your if statement encapsulated in quotes. That means that PHP won’t interpret it. Instead, it will print it out along with your HTML.
Something along the lines of this will work better:
By the way, where are you getting $menuID from?