Reputation: 21
I have a page with a persisted left nav that is populated based on a database. I need to visually mark the menu entry that corresponds with the content currently presented on the right side of the page. I am having problems getting the check of current page to work. (I am learning PHP and attempting to edit someone else's code, person long gone.)
Here is the code for the menu:
while( ( $row = mysql_fetch_array( $result ) ) && ( $count < $limit ) ) {
$count++;
echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&action=show&id=" . $row['id'] . "\" >" . stripslashes( $row['title'] ) . "</a></li>\n";
..etc. Works fine to generate menu list. Then I think what I want to do is to compare the URI this code produces with the currently loaded page, to determine if I should add a CSS style for current page or not.
So I attempted this:
echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&action=show&id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == "$this" ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";
Got syntax errors. So tried this:
echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&action=show&id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == $this ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";
Still syntax errors. So tried this:
echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&action=show&id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == $row['id'] ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";
Suggestions?
Upvotes: 1
Views: 201
Reputation: 21
Success at last. I found a way to get this to work, though the code may be less than elegant. I could not get the comparison of the URI and the $row['id'] to work within the echo statement. So I created a separate function to do the comparison and returned the result to the echo statement as follows:
echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&action=show&id=" . $row['id'] . "\"" . $this->checkRow($row['id']) . ">" . stripslashes( $row['title'] ) . "</a></li>\n";
function checkRow($myID)
{
if( strstr( $_SERVER['REQUEST_URI'], $myID ) )
{
return " class=\"selected\"";
}
}
Upvotes: 1
Reputation: 24713
You have php tags in your echo statement in your first example
echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&action=show&id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == "$this" ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";
try this
echo "\t\t\t<li><a href=\"".NEWS_URL."?show=news&action=show&id=".$row['id']."\". ($_SERVER['REQUEST_URI'] == $this ?"class=\"selected\"" :"").stripslashes( $row['title'] )."</a></li>\n";
Upvotes: 0