将结果基于mysql中的行号定位

时间:2014-03-22 20:57:43

标签: php mysqli

我有这个功能(参见下文)

function showMenu(){
$result = mysqli_query($con,"SELECT * FROM user_menu");
$menu = '<nav id="main-menu"><ul class="menuwrapper extend">';
while($row = mysqli_fetch_array($result))
{
    $menu .= '<li class="' . $row['status'] . '"><a href="' . $row['url'] . '" class="extend" title="' . $row['url'] . '">' . $row['name'] . '</a></li>';
}
$menu .= '</ul></nav>';

return $menu;
}

我的数据库表的结构如下(参见下文)

id(BigInt 100, AUTO_INCREMENT, PRIMARY)
name(text, utf8_general_ci)
url(varchar 100, utf8_general_ci)
status(text, utf8_general_ci)
key(int 30)

该表的内容是(参考 下文)

id = "1", name = "Post", url = "http://localhost/gadgetmarket/admin/index.php", status="default", key = "0"
id = "2", name = "Pages", url = "http://localhost/gadgetmarket/admin/pages.php", status="parent", key = "1"
id = "3", name = "Menus", url = "http://localhost/gadgetmarket/admin/menus.php", status="parent", key = "2"
id = "4", name = "Theme", url = "http://localhost/gadgetmarket/admin/theme.php", status="parent", key = "3"

现在,我的问题是如何根据每个菜单上的键号输出结果?我的预期输出基于我试图从上面的数据实现的是(参见下文)

<nav id="main-menu">
    <ul class="menuwrapper extend">
        <li class="default">
            <a href="http://localhost/gadgetmarket/admin/index.php" class="extend" title="http://localhost/gadgetmarket/admin/index.php">Post</a>
        </li>
        <li class="parent">
            <a href="http://localhost/gadgetmarket/admin/pages.php" class="extend" title="http://localhost/gadgetmarket/admin/pages.php">Pages</a>
        </li>
        <li class="parent">
            <a href="http://localhost/gadgetmarket/admin/menus.php" class="extend" title="http://localhost/gadgetmarket/admin/menus.php">Menus</a>
        </li>
        <li class="parent">
            <a href="http://localhost/gadgetmarket/admin/theme.php" class="extend" title="http://localhost/gadgetmarket/admin/theme.php">Theme</a>
        </li>
    </ul>
</nav>

正如您所看到的,输出是根据键顺序排列的。任何建议,建议和想法将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您没有在函数中声明全局连接

function showMenu(){
global $con; // SIMPLY ADD THIS LINE
$result = mysqli_query($con,"SELECT * FROM user_menu");
$menu = '<nav id="main-menu"><ul class="menuwrapper extend">';
while($row = mysqli_fetch_array($result))
{
    $menu .= '<li class="' . $row['status'] . '"><a href="' . $row['url'] . '"     class="extend" title="' . $row['url'] . '">' . $row['name'] . '</a></li>';
}
$menu .= '</ul></nav>';

return $menu;
}

您可以使用ORDER BY以您希望的方式获取数据 SELECT * FROM user_menu ORDER BY key ASC