【问题标题】:Database driven PHP menu with check for current page带有检查当前页面的数据库驱动的 PHP 菜单
【发布时间】:2013-09-02 19:18:35
【问题描述】:

我有一个基于数据库填充的带有持久左导航的页面。我需要直观地标记与页面右侧当前呈现的内容相对应的菜单项。我在检查当前页面时遇到问题。 (我正在学习 PHP 并试图编辑别人的代码,这个人早就走了。)

这里是菜单的代码:

while( ( $row = mysql_fetch_array( $result ) ) && ( $count < $limit ) ) {
    $count++;
    echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&amp;action=show&amp;id=" . $row['id'] . "\" >" . stripslashes( $row['title'] ) . "</a></li>\n";

..等等。可以很好地生成菜单列表。 然后我想我想做的就是将这段代码生成的 URI 与当前加载的页面进行比较,以确定是否应该为当前页面添加 CSS 样式。

所以我尝试了这个:

echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&amp;action=show&amp;id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == "$this" ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";

出现语法错误。所以尝试了这个:

echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&amp;action=show&amp;id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == $this ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";

仍然有语法错误。所以尝试了这个:

echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&amp;action=show&amp;id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == $row['id'] ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";

建议?

【问题讨论】:

  • 澄清一下,您已将NEWS_URL 预定义为我信任的常量?

标签: php database menu compare uri


【解决方案1】:

终于成功了。我找到了一种让它工作的方法,尽管代码可能不够优雅。 我无法在 echo 语句中比较 URI 和 $row['id']。所以我创建了一个单独的函数来进行比较,并将结果返回给 echo 语句,如下所示:

echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&amp;action=show&amp;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\"";
 }
}

【讨论】:

    【解决方案2】:

    在您的第一个示例中,您的 echo 语句中有 php 标签

    echo "\t\t\t<li><a href=\"" . NEWS_URL . "?show=news&amp;action=show&amp;id=" . $row['id'] . "\" <?php if( $_SERVER['REQUEST_URI'] == "$this" ) echo " class=\"selected\""; ?>>" . stripslashes( $row['title'] ) . "</a></li>\n";
    

    试试这个

    echo "\t\t\t<li><a href=\"".NEWS_URL."?show=news&amp;action=show&amp;id=".$row['id']."\".  ($_SERVER['REQUEST_URI'] == $this ?"class=\"selected\"" :"").stripslashes( $row['title'] )."</a></li>\n";
    

    【讨论】:

    • 谢谢,向量。我试过了,它不起作用。我想知道我们是否可能在其中某处丢失了开始锚标记上的右括号?
    • 这是我最近的尝试(不成功):'echo "\t\t\t
    • " 。带斜线($row['title'])。 "
    • \n";'我收到有关此 Parse 错误的错误消息:语法错误,意外 T_CLASS,期望 ',' 或 ';'
  • 我也试过(不成功): 'if($_SERVER['REQUEST_URI'], $this !== false) "class=\"selected\"" 。 ">" 。带斜线($row['title'])。 "\n";'现在已经花了数小时/数天试图让它发挥作用。不明白他们为什么不发布现实的代码示例......
  • 你修好了吗?
  • 没有。我尝试的一切都失败了。
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签